forked from sowon-dev/AlgorithmStudy_Java
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSumvsXOR.java
More file actions
47 lines (42 loc) ยท 1.09 KB
/
SumvsXOR.java
File metadata and controls
47 lines (42 loc) ยท 1.09 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
47
package hackerrank;
public class SumvsXOR {
static long sumXor(long n) {
//์ด์ง์์ ๋
ผ๋ฆฌ์ฐ์ฐ
//sol1 => Time limit exceeded
/*
long cnt = 0;
for (int i = 0; i <= n; i++) {
if ( (n + i) == (n ^ i)) {
cnt++;
}
}
return cnt;
*/
//sol2
long count = 0;
//10์ง๋ฒ์ ์ง์์ธ ๊ฒฝ์ฐ 2์ง๋ฒ์์ ๋ง์ง๋ง ๋นํธ๊ฐ 0์ด๋ค. count์ 1์ฆ๊ฐ์ํจ๋ค.
//This performs a basic conversion from int to binary using divide by two and checking even or odd
while(n != 0){
count += (n%2 == 0)? 1:0;
n/=2;
}
// Math.pow(a,b)๋ a์ b์น
count = (long) Math.pow(2,count);
return count;
}
/* (10์ง๋ฒ) 4 => (2์ง๋ฒ) 100
* 0 => 0
* 1 => 101 = 5
* 2 => 110 = 6
* 3 => 111 = 7
* */
public static void main(String[] args) {
long n;
System.out.println(sumXor(4) + ", ans: 4");
System.out.println(sumXor(5) + ", ans: 2");
n = 1000000000000000L;
System.out.println(sumXor(n) + ", ans: 1073741824");
n = 3434444444333L;
System.out.println(sumXor(n) + ", ans: 262144");
}
}