Tuesday, December 20, 2011

Number is multiple of 10 or not

Write an efficient C program to check whether a number is a multiple of 10 or not

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

2 comments:

  1. 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.

    ReplyDelete
  2. int isMultipleOf3(int n)
    {
    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));
    }

    ReplyDelete