Check if a number is divisible by 3

后端 未结 16 2920
予麋鹿
予麋鹿 2020-12-01 01:30

I need to find whether a number is divisible by 3 without using %, / or *. The hint given was to use atoi() function. Any

16条回答
  •  执念已碎
    2020-12-01 02:06

    My solution in Java only works for 32-bit unsigned ints.

    static boolean isDivisibleBy3(int n) {
      int x = n;
      x = (x >>> 16) + (x & 0xffff); // max 0x0001fffe
      x = (x >>> 8) + (x & 0x00ff); // max 0x02fd
      x = (x >>> 4) + (x & 0x000f); // max 0x003d (for 0x02ef)
      x = (x >>> 4) + (x & 0x000f); // max 0x0011 (for 0x002f)
      return ((011111111111 >> x) & 1) != 0;
    }
    

    It first reduces the number down to a number less than 32. The last step checks for divisibility by shifting the mask the appropriate number of times to the right.

提交回复
热议问题