leetcode (Binary Gap)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/hsx1612727380/article/details/85606669

Title:Binary Gap    868

Difficulty:Easy

原题leetcode地址:   https://leetcode.com/problems/binary-gap/

1.  数学公式

时间复杂度:O(n),两次一层for循环,最长遍历长度为n。

空间复杂度:O(1),没有申请额外空间。

    /**
     * 先转换成二进制,再求距离
     * @param N
     * @return
     */
    public static int binaryGap(int N) {

        String s = Integer.toBinaryString(N);
        int count = 0;
        int index = 0;

        for (int i = 0; i < s.length(); i++) {
            if (s.charAt(i) == '1') {
                index = i;
                break;
            }
        }

        for (int i = index + 1; i < s.length(); i++) {
            if (s.charAt(i) == '1') {
                count = Math.max(count, i - index);
                index = i;
            }
        }

        return count;
    }

猜你喜欢

转载自blog.csdn.net/hsx1612727380/article/details/85606669
GAP
GAP