Skip to content

Instantly share code, notes, and snippets.

@abdurrahmanekr
Created April 6, 2022 10:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save abdurrahmanekr/a0635cda8b7b9aa49dec0e6de5124e56 to your computer and use it in GitHub Desktop.
Save abdurrahmanekr/a0635cda8b7b9aa49dec0e6de5124e56 to your computer and use it in GitHub Desktop.
/*
* Question:
* Subtract given two positive integer as string without using `atoi` or number parser `parseInt, parseFloat` and return signed integer as string.
* Data types:
* - function subtract(num1: unsigned integer as String, num2: unsigned integer as string) : signed integer as string
* Rules:
* - Don't use atoi or parseInt for inputs directly
* Duration:
* - 45 minutes
* Examples:
* - subtract('1000', '10000') //-9000
* - subtract("123", '123') // 0
* - subtract('336651231281827315348592312318953984723125348123', '1') //336651231281827315348592312318953984723125348122
* Submission:
* Please share your code on a public platform and send access link to alperen@base64.ai via email.
*/
let subtract = (num1,num2) => {
if (num1 == num2)
return '0';
const isSmall = (n1, n2) => {
const n1len = n1.length;
const n2len = n2.length;
if (n1len > n2len)
return false;
else if (n1len < n2len)
return true;
for (let i = 0; i < n1len; i++) {
if (n1[i] < n2[i])
return true;
else if (n1[i] > n2[i])
return false;
}
return false;
};
debugger;
let big = isSmall(num1, num2) ? num2 : num1;
let small = isSmall(num1, num2) ? num1 : num2;
let biglen = big.length;
let smalllen = small.length;
big = big.split('').reverse().join("")
small = small.split('').reverse().join("")
const realDiff = [];
for (let i = 0; i < smalllen; i++) {
let diff = big[i] - small[i];
// elde al
if (diff < 0) {
let foo = parseInt(big[i+1]) - 1;
for (let j = i+1; foo < 0; j++) {
foo = parseInt(big[j]) - 1;
if (foo >= 0) {
let tmp = big.split('');
tmp[j] = foo;
big = tmp.join('')
}
}
if (isNaN(foo)) {
diff = 0;
}
else {
diff = parseInt(big[i]) + 10 - small[i];
}
realDiff.push(diff);
}
else {
realDiff.push(diff);
}
}
if (big.replace(/0/g, '') === '') {
for (let i = 1; i < biglen - smalllen; i++) {
realDiff.push(9);
}
}
realDiff.push(big.slice(smalllen, biglen));
return realDiff.reverse().join('');
}
console.log(subtract('1000', '10000'),subtract('1000', '10000') === '-9000')
console.log(subtract('123', '123'),subtract('123', '123') === '0')
console.log(subtract('336651231281827315348592312318953984723125348123', '1'),
subtract('336651231281827315348592312318953984723125348123', '1') === '336651231281827315348592312318953984723125348122')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment