算法基础 - 第一天 - Binary gap

题目来源:Codility

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:

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).

// my code...
public static int solution(int N) {
    String strn = Integer.toBinaryString(N);
    while (strn.endsWith("0"))
        strn = strn.substring(0, strn.length() - 1);
    String[] strArray = strn.split("1+");

    int gap = 0;

    for (int i = 0; i < strArray.length; i++) {
        if (strArray[i].length() > gap) {
            gap = strArray[i].length();
        }
    }

    return gap;
}


// code on codility by Akan
public static int solution(int N) {
    // note "0+$" delete the 0s in the end of the binary string, if the string
    // originally ends with 0. Note that only the 0s sorrounded by 1s are calculated
    return Stream.of(
        Integer.toBinaryString(N).replaceAll("0+$","").split("1+"))
        .filter(a -> a != null)
        .max(Comparator.comparingInt(String::length))
        .map(String::length)
        .orElse(0);
}

// but this might be easier to read
public static int solution(int N) {
        return Stream.of(
            Integer.toBinaryString(N).replaceAll("0$", "").split("1+"))
            .filter(a -> a != null)
            .mapToInt(a -> a.length()).max().orElse(0);
}




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值