int f(int a)
{
int b = 0;
while (a >>= 1)
{
b++;
}
return b;
}
case1> 1100 (b==0)->0110 (b==1)->0011 (b==2)->0001 (b==3)->0000 : return 3
case 2> 1000 (b==0)->0100 (b==1)->0010 (b==2)->0001 (b==3)->0000 : return 3
This function returns the position of the leftmost '1' bit in input a.
Now, let's consider when 'while' statement can be infinite. Zero, with no non-zero bit, returns 0. A negative number throws the computer into an infinite loop. See below.
Signed 4bits integer
+7 : 0111
+6 : 0110
+5 : 0101
+4 : 0100
+3 : 0011
+2: 0010
+1 : 0001
+0: 0000
0 : n/a
-0 : 1111
-1 : 1000
-2 : 1001
-3 : 1011
-4 : 1100
-5 : 1101
-6 : 1110
-7 : 1111
Unsigned 4 bits integer
+15 : 1111
:
+7 : 0111
:
+1 : 0001
+0 : n/a
0 : 0000
No comments:
Post a Comment