`

Longest Consecutive 1s in Binary

阅读更多

Find the longest continuous subsequence of 1's in binary representation of an integer.

Solution 1:

 

public int countConsecutive1s(int n) {
	if(n == 0) return 0;
	int max = 0;
	int len = 0;
	for(int i=0; i<32; i++) {
		int v = (n >>> i) & 1;
		if(v == 1) {
			len++;
			max = Math.max(len, max);
		} else {
			len = 0;
		}
	}
	return max;
}

 

 

Solution 2:

To determine the length of the longest sequence of consecutive 1's, this is more efficient:

def longest_one_chain(n)
  c = 0
  while n != 0
    n &= n >> 1
    c += 1
  end
  c
end

 

The method simply counts how many times you can "bitwise AND" the number with itself shifted 1 bit to the right until it is zero.

Example:

                 ______ <-- longest chain
    01011011100001111110011110101010 c=0
AND  0101101110000111111001111010101
        1001100000111110001110000000 c=1, 1’s deleted
AND      100110000011111000111000000
            100000011110000110000000 c=2, 11’s deleted
AND          10000001111000011000000
                    1110000010000000 c=3, 111’s deleted
AND                  111000001000000
                     110000000000000 c=4, 1111’s deleted
AND                   11000000000000
                      10000000000000 c=5, 11111’s deleted
AND                    1000000000000
                                   0 c=6, 111111’s deleted

Reference:

http://stackoverflow.com/questions/10911780/looping-through-bits-in-an-integer-ruby/10922528

http://www.quora.com/How-can-we-find-the-longest-continuous-subsequence-of-0s-in-binary-representation-of-an-integer-in-O-log-n-time-complexity

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics