Home > Blockchain >  Why does my variable return null instead of the defined value
Why does my variable return null instead of the defined value

Time:04-05

Does anyone know why my "Carry" variable in the code returns NAN instead of 0

var addBinary = function(a, b) {
  let i = a.length - 1
  let j = b.length - 1

  let result = []
  var carry = 0;
  while (i >= 0 || j >= 0) {
    if (i == 0) {
      console.log(carry)
    }

    let sum = carry

    if (i >= 0) {
      sum = sum   parseInt(a[i])
    }

    if (j >= 0) {
      sum  = parseInt(b[i])
    }

    result.unshift(parseInt(sum) % 2)
    carry = parseInt(sum) / 2
    i--
    j--
  }

  if (carry > 0) {
    result.unshift(1)
  }
  // console.log(result)
  return result.toString()
};

addBinary('11', '1')

console.log(carry) should return 0 and not NAN. I can't seem to find the issue, sure I am missing something

CodePudding user response:

The reason console.log(carry) returns Nan is because you wrote: carry = parseInt(sum) / 2; This redefines carry to Nan instead of 0 (first time you go through the while loop carry is 0, but second time it is Nan). parseInt(sum) returns null (Nan), because at another point you wrote b[i] instead of b[j].

CodePudding user response:

try this

var addBinary = function(a, b) {
  let i = a.length - 1
  let j = b.length - 1
  
  let result = []
  var carry = 0;
  while(i >= 0 || j >= 0){
        if(i == 0){
          console.log(carry)
      }
      
       let sum = carry
       
     
      if(i >= 0){
          sum = sum   parseInt(a[i])
      }
      
       
      
      if(j >= 0){
          
          sum  = parseInt(b[i])
      }
      
     
      result.unshift(parseInt(sum)%2)
      
      carry = parseInt(sum)/2
      i--
      j--
  }
  
  if(carry > 0){
      result.unshift(1)
  }
  console.log(carry);
  // console.log(result)
  return result.toString();
};


    addBinary('11','1'); // output NaN
    addBinary(11,1); // as we are passing numbers no quotes are needed expected output 0
  • Related