码迷,mamicode.com
首页 > 其他好文 > 详细

BinaryGap

时间:2016-09-21 15:46:53      阅读:176      评论:0      收藏:0      [点我收藏+]

标签:

Task description

binary gap within a positive integer N is any maximal sequence of consecutive zeros that is surrounded by ones at both ends in the binary representation of N.

For example, number 9 has binary representation 1001 and contains a binary gap of length 2. The number 529 has binary representation 1000010001 and contains two binary gaps: one of length 4 and one of length 3. The number 20 has binary representation 10100 and contains one binary gap of length 1. The number 15 has binary representation 1111 and has no binary gaps.

Write a function:

class Solution { public int solution(int N); }

that, given a positive integer N, returns the length of its longest binary gap. The function should return 0 if N doesn‘t contain a binary gap.

For example, given N = 1041 the function should return 5, because N has binary representation 10000010001 and so its longest binary gap is of length 5.

Assume that:

  • N is an integer within the range [1..2,147,483,647].

Complexity:

  • expected worst-case time complexity is O(log(N));
  • expected worst-case space complexity is O(1).

The obvious solution for this is to convert input integer to its binary representation, and then traverse the generated array to get the maximum number of zeros between ones. But we can also solve without convertion. We know that a zero in a binary number represents a multiple of two, while a one represents a multiple of two with an adder of one. So we can just simply count how many times that this integer can be divided completely between two residus of division by two. So below is the solution:

 1 class Solution {
 2     public int solution(int N) {
 3         int test =N;
 4         int ml =0;
 5         int t = 0;        
 6         boolean power = false;
 7         if(test%2==0){
 8             test/=2; 
 9             power =true;
10         }
11 
12         while(test!=0){
13             if(test%2 == 0){
14                 if(power){
15                     test/=2;
16                     continue;
17                 }
18                 t++;
19             }else{
20                 power =false;
21                 t=0;
22             }
23             test/=2;
24             if(ml<t){
25                 ml =t;
26             }
27         }
28         return ml;
29     }
30 }

The time complexity is O(log(n)) and memory complexity is a constant of O(C).

 

BinaryGap

标签:

原文地址:http://www.cnblogs.com/wizardkeven/p/binary.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!