+6

# The following outputs 11, 704 and 124 but I can't wrap my head around the reason for their output. Please help a brother..

function addBinary(a,b) { var sum=a+b; var res=””; while(sum>0) { res=sum%2+res; sum=Math.floor(sum/ 2); } } alert(addBinary(1,2)); //11 var input=407; var res=0; for(i=input;i>0;i=Math.floor(i/10)) { res=res*10+i%10; } document.write(res); //704 var arr=[1]; for(var i=1; i<3; i++) { arr[i] = arr[i-1]+i; } alert(arr.join(“”)); //124

7/11/2019 9:12:55 PM

Mofey

+7

I'm trying to explain third program. var arr = [1]; // arr[0] = 1; The loop start with i = 1 and arr[i] = arr[i-1] + 1 is arr[1] = arr[1-1] + 1 = 1+1=2 Next step i = 2. arr[i] = arr[i-1] + 1 is arr[1] = arr[2-1] + 1 = 2+2=4.

+6

Look inside the loop you have arr [i] = arr [i-1] + i. So arr [i-1] is 1 and plus i.

+3

You probably wanted to write i > 0, since that actually makes sense i in the loop starts as 407. res is 0, so res * 10 + i % 10 is 7. Then, at the end of the iteration, i becomes Math.floor(i / 10), which is 40. res * 10 + i % 10 is 70, since 7 * 10 (70) + 40 % 10 (0) is 70. Then, again, i becomes i / 10 (4). res * 10 + i % 10 = 70 * 10 (700) + i % 10 (4) = 704. 4 divided by 10 is 0(.4), so the loop stops executing. (it gets reversed)

+3

arr[0] = 1 arr[1] = arr[0] + 1 -> 2 arr[2] = arr[1] + 2 -> 4

+3

Ahmadjon Boboev, why are we adding 1+1 and 2+2?

+2

Alright, I got that so how about the other two programs

+2

Alright, maybe I'll understand better by helping me out with this question Ahmadjon Boboev, Qasem and Airree, https://www.sololearn.com/Discuss/1882877/?ref=app

+1

The first code simply converts the sum of function arguments to it's binary representation as follow: To convert a number to binary form we must take modules of number by 2 and then reduce that number for next step. In this example for sum = 3 we have: 3%2=1. So the least significant digit of binary form is 1. To continue we must reduce the number as: [3/2]=1 (And this is a general rule for other basements too (remeber your question and ruduction in base 10)) And continue this process until sum become 0.