1. BinaryGap Find longest sequence of zeros in binary representation of an integer.

A 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).
package com.codility;
public class Test01 {
    public int solution(int N) {
        if(N<=0){
            return 0;
        }
        String str = Integer.toBinaryString(N);
        int size = str.length();
        int count=0;
        int max = 0;
        for(int i=0;i<size;i++){
            String str01 = str.substring(i, i+1);
            if(str01.equals("1")){
                if(count>0){
                    max = Math.max(count, max);
                }
                count = 0;
            }
            if(str01.equals("0")){
                count ++;
            }
        }
        return max;
    }
    public static void main(String[] args) {
        String str = Integer.toBinaryString(20);
        System.out.println(str);
//        System.out.println(str.substring(0, 1));
        Test01 t01 = new Test01();
        System.out.println(t01.solution(5));
        System.out.println(t01.solution(20));
        System.out.println(t01.solution(529));
    }
}
时间: 2024-12-29 11:34:27

1. BinaryGap Find longest sequence of zeros in binary representation of an integer.的相关文章

LeetCode | 1372. Longest ZigZag Path in a Binary Tree二叉树中的最长交错路径【Python】

LeetCode 1372. Longest ZigZag Path in a Binary Tree二叉树中的最长交错路径[Medium][Python][DFS] Problem LeetCode Given a binary tree root, a ZigZag path for a binary tree is defined as follow: Choose any node in the binary tree and a direction (right or left). I

2018.3.5-6 knapsack problem, sequence alignment and optimal binary search trees

这周继续dynamic programming,这三个算法都是dynamic programming的. knapsack problem有一种greedy的解法,虽然简单但是不保证正确,这里光头哥讲的是dynamic的解法.其实和上次那个max weight independent set的算法差不多,同样是每个物件都判断一遍有这个物件和没这个物件两种情况,用bottom-up的方法来解,然后得到一个最大的value值,这时因为没有得到具体的选择方案,所以最后还需要一部重构的步骤得到具体方案.

python help(__builtins__)

Help on built-in module builtins: NAME builtins - Built-in functions, exceptions, and other objects. DESCRIPTION Noteworthy: None is the `nil' object; Ellipsis represents `...' in slices. CLASSES object BaseException Exception ArithmeticError Floatin

python_builtins

python内置函数 # encoding: utf-8 # module builtins # from (built-in) # by generator 1.145 """ Built-in functions, exceptions, and other objects. Noteworthy: None is the `nil' object; Ellipsis represents `...' in slices. """ # no

uvalive 6300 Signed Binary Representation of Integers

6300 Signed Binary Representation of IntegersComputing ax mod n for large integers x and n is the most time-consuming process in most public-keycryptography systems. An algorithm to compute ax mod n can be described in a C-like pseudo-code asfollows.

4.内置函数总结

1 def abs(*args, **kwargs): # real signature unknown 2 """ Return the absolute value of the argument. """ 3 pass 4 #abs(*args, **kwargs)#返回参数的绝对值,可接收任何数据类型 5 #?绝对值如何接收数值意外的类型得到什么样的结果.(报错,应该是不可接收) 6 7 def all(*args, **kwargs):

[codility] Lession1 - Iterations - BinaryGap

Task1: A 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

BinaryGap

Task description A 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 bina

Ducci Sequence解题报告

A Ducci sequence is a sequence of n-tuples of integers. Given an n-tuple of integers (a1, a2, ... , an), the next n-tuple in the sequence is formed by taking the absolute differences of neighboring integers: ( a1, a2, ... , an)  (| a1 - a2|,| a2 - a3