Write an efficient C program to check whether a number is a multiple of 10 or not
I end up with 120 (12*10).
Thus
Solution:
If i have an integer, say 12, and I perform the following bit-manipulation on it:int i = 12;
i = (i << 3) + (i << 1);
I end up with 120 (12*10).
Thus
i = (i << 3) + (i << 1);
i = (i * 8) + (i * 2);
i = 8i + 2i
i = 10i
If difference between count of odd set bits (Bits set at odd positions) and even set bits is multiple of 3 then is the number.
ReplyDeleteint isMultipleOf3(int n)
ReplyDelete{
int odd_count = 0;
int even_count = 0;
if(n < 0) n = -n;
if(n == 0) return 1;
if(n == 1) return 0;
while(n)
{
if(n & 1)
odd_count++;
n = n>>1;
if(n & 1)
even_count++;
n = n>>1;
}
return isMultipleOf3(abs(odd_count - even_count));
}