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

后端 未结 10 1419
清歌不尽
清歌不尽 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 16:46

    A number is divisible by three if its binary alternating digit sum is zero:

    bool by3(int n) {
      int s=0;
      for (int q=1; n; s+=q*(n&1), n>>=1, q*=-1);
      return !s;
    }
    

提交回复
热议问题