Java 给定数字中连续1的最大数目 public int tobinary(int x) { 整数计数=0; 而(x!=0) { x=(x&(x)

Java 给定数字中连续1的最大数目 public int tobinary(int x) { 整数计数=0; 而(x!=0) { x=(x&(x),java,binary,decimal,Java,Binary,Decimal,正如我们所知,x=(x&(x因此,对于while循环中的每个迭代, x=x(和运算符)(2*x) 例如,当x=7时 计数=0 110111101 // initial x, longest sequence 4 1101111010 // x << 1, count 1 100111000 // new x, longest sequence 3 1001110000 // x << 1, count 2 110000 // new x, longest se

正如我们所知,
x=(x&(x因此,对于while循环中的每个迭代,
x=x(和运算符)(2*x)

例如,当x=7时 计数=0

 110111101 // initial x, longest sequence 4
1101111010 // x << 1, count 1
 100111000 // new x, longest sequence 3
1001110000 // x << 1, count 2
    110000 // new x, longest sequence 2
   1100000 // x << 1, count 3
    100000 // new x, longest sequence 1
   1000000 // x << 1, count 4
         0 // new x, end of loop

这就是7分3的方法。首先,方法名称有误导性。
x     : 0000 0111
x << 1: 0000 1110
-----------------
     &: 0000 0110
count = 1
x     : 0000 0110
x << 1: 0000 1100
-----------------
     &: 0000 0100
count = 2

x     : 0000 0100
x << 1: 0000 1000
-----------------
     &: 0000 0000
count = 3, exit loop and return.
 110111101 // initial x, longest sequence 4
1101111010 // x << 1, count 1
 100111000 // new x, longest sequence 3
1001110000 // x << 1, count 2
    110000 // new x, longest sequence 2
   1100000 // x << 1, count 3
    100000 // new x, longest sequence 1
   1000000 // x << 1, count 4
         0 // new x, end of loop
Iteration 1:

//x = 7 & 14 which results in 6 ie

0111
1110 (AND)
-------
0110 => 6
-------
count = 1

Iteration 2:

//x = 6 & 12 results in 4

0110
1100 AND
-------
0100 => 4
-------
count = 2

Iteration 3:
// x = 4 & 8 results in 0

0100
1000 AND
-----
0000 
-----
count = 3