-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMultipleOf3.java
More file actions
46 lines (42 loc) · 1.06 KB
/
MultipleOf3.java
File metadata and controls
46 lines (42 loc) · 1.06 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
package math;
/**
* Find out if the given number is multiple of three or not. If the difference
* between the number of ones in the odd places and number of ones in the even
* places for the binary representation of a number are a multiple of 3, then so
* is the number itself. Same can also be applied to multiples of k, in which
* represent it in base k-1.
*
* Link:
* http://www.geeksforgeeks.org/write-an-efficient-method-to-check-if-a-number-
* is-multiple-of-3/
*
* @author shivam.maharshi
*/
public class MultipleOf3 {
/**
* Complexity of this solution is O(lg(n)).
*/
public static boolean isMultiple(int n) {
int even = 0;
int odd = 0;
boolean isEven = true;
while (n != 0) {
if (isEven) {
if ((n & 1) == 1) {
even++;
}
isEven = false;
} else {
if ((n & 1) == 1) {
odd++;
}
isEven = true;
}
n = n >> 1;
}
return ((odd - even) % 3 == 0) ? true : false;
}
public static void main(String[] args) {
System.out.println(MultipleOf3.isMultiple(332));
}
}