-
Notifications
You must be signed in to change notification settings - Fork 17
/
Reduce.java
47 lines (38 loc) · 993 Bytes
/
Reduce.java
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
import java.lang.*;
public class Main {
public static void main(String args[]) {
System.out.println(reduceEff2(15));
}
static int reduceEff(int n) {
int ans = 0;
while(n != 1) {
if((n&1) == 0) {
n /= 2;
} else if( n == 3) {
n -= 1;
} else if( n%4 == 1) {
n -= 1;
} else if( n%4 == 3) {
n += 1;
}
ans++;
}
return ans;
}
static int reduceEff2(int n) {
int ans = 0;
while(n != 1) {
if((n&1) == 0) {
n /= 2;
} else if( n == 3) {
n -= 1;
} else if( (n&3) == 1) { // 4x + 1 in binary - _________01 3 - 000000000011
n -= 1;
} else if( (n&3) == 3) { // 4x + 3 in binary - _________11
n += 1;
}
ans++;
}
return ans;
}
}