How to check if an integer can be divided by 3

后端 未结 8 1152
不知归路
不知归路 2020-12-29 03:47

How to check if my integer can be divided by 3 as below:

for(int i=0; i<24;  i++){
   //here, how to check if \"i\" can be divided by 3 completely(e.g. 3,         


        
8条回答
  •  一个人的身影
    2020-12-29 04:38

    Well, what you could do (it might be a bit faster; it is faster on my machine) is:

    boolean canBeDevidedBy3 = ((int) (i * 0x55555556L >> 30) & 3) == 0;
    

    instead of

    boolean canBeDevidedBy3 = (i % 3) == 0;
    

    However, the multiplication trick only works for -2 <= i <= 1610612735. This answer was inspired by this optimization question. But if I can give you a tip: use (i % 3) == 0. It's so much simpler, and will always work.

提交回复
热议问题