Logic to check the number is divisible by 3 or not?

后端 未结 10 1418
清歌不尽
清歌不尽 2021-01-14 16:31

without using %, / or * , I have to find the no. is divisible by 3 or not?

it might be an interview question.

Thanks.

10条回答
  •  不思量自难忘°
    2021-01-14 17:03

    Suppose n is the number in question and it is non-negative.

    If n is 0 it is divisible by 3; otherwise n = (2^p)*(2*n1+1) and n is divisible by 3 iff 2*n1+1 is, iff there is a k>=0 with 2*n1+1 = 3*(2*k+1) iff n1 = 3*k+1 iff n1=1 or n1> 1 and n1-1 is divisible by 3. So:

    int ism3( int n)
    {   for(;n;)
        {    while( !(n & 1)) n >>= 1;
             n >>= 1;
             if ( n == 0) return 0;
             n-= 1;
        }
        return 1;
     }
    

提交回复
热议问题