-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathBinaryGap
70 lines (61 loc) · 1.34 KB
/
BinaryGap
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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
//BinaryGap
class Solution
{
public int solution(int N)
{
int gap = 0; //兩個1間隔
int maxgap = 0; //兩個1最大間隔
String b = Integer.toBinaryString(N); //化成binarybit
for(int i = 1 ; i < b .length(); i++) //檢查每個字串
{
if(b.charAt(i)=='1') //如果某個字=1
{
if(gap > maxgap)
{
maxgap = gap;
}
gap = 0; //間隔重新計算
}else //如果某個字為0
{
gap =gap +1;
}
}
return maxgap;
}
}
//
class Solution {
public int solution(int N)
{
int b;
int zeroCounter = 0;
int prev = 0;
int c = -1;
while (N != 0)
{
b = N % 2;
N = N / 2;
if ((b==1)||(c==0))
{
c=0;
//System.out.print(b);
if (b == 1)
{
//checkTrailZero=prev;
if (prev < zeroCounter)
{
prev = zeroCounter;
}
zeroCounter = 0;
}
else
{
zeroCounter++;
//System.out.print(zeroCounter);
}
}
}
//System.out.print(prev);
return prev;
}
}