Bitwise addition of large numbers in JavaScript causes negative result

Viewed 27

I'm working on an interview question which requires me to add to strings using bitwise operators. My code below works just fine for small numbers (from 0 up to 123456789). However if I try to add 1234567890 + 1234567890, surprisingly I get a negative result. I'm guessing that this is due to Javascript's 32bit limitation.

I tried to split the input numbers by dividing them by 2 for example but it leads to wrong computation. Is there a way to properly split the input numbers and add them later on at the end of the computation?

const addStrings = (s1, s2) => {
  let sum = s1 ^ s2
  let carry = (s1 & s2) << 1 

  if (sum & carry) {
    return addStrings(sum, carry)
  } else {
    return (sum ^ carry)
  }

}
0 Answers
Related