当前位置:网站首页>Force deduction solution summary 868- binary spacing

Force deduction solution summary 868- binary spacing

2022-06-12 02:08:00 Lost summer

Directory links :

Force buckle programming problem - The solution sums up _ Share + Record -CSDN Blog

GitHub Synchronous question brushing items :

https://github.com/September26/java-algorithms

Original link : Power button


describe :

Given a positive integer n, Find and return to n In the binary representation of adjacent 1 Between Longest distance . If there are no two adjacent 1, return 0 .

If only 0 Put two 1 Separate ( May not exist 0 ), We think these two 1 each other adjacent . Two 1 The distance between them is the absolute difference of their positions in the binary representation . for example ,"1001" Two of them 1 The distance to 3 .

Example 1:

Input :n = 22
Output :2
explain :22 The binary of is "10110" .
stay 22 In the binary representation of , There are three 1, Make up two adjacent pairs of 1 .
The first pair of adjacent 1 in , Two 1 The distance between is 2 .
The second pair is adjacent 1 in , Two 1 The distance between is 1 .
The answer is the largest of the two distances , That is to say 2 .
Example 2:

Input :n = 8
Output :0
explain :8 The binary of is "1000" .
stay 8 There are no adjacent two in the binary representation of 1, So back 0 .
Example 3:

Input :n = 5
Output :2
explain :5 The binary of is "101" .
 

Tips :

1 <= n <= 109

source : Power button (LeetCode)
link :https://leetcode-cn.com/problems/binary-gap
Copyright belongs to the network . For commercial reprint, please contact the official authority , Non-commercial reprint please indicate the source .

Their thinking :

*  Their thinking :
*  To string, Then judge the distance 

Code :

public class Solution868 {

    public int binaryGap(int n) {
        char[] chars = Integer.toString(n, 2).toCharArray();
        int result = 0;
        int currentIndex = 0;
        for (int i = 0; i < chars.length; i++) {
            char aChar = chars[i];
            if (aChar == '0') {
                continue;
            }
            result = Math.max(i - currentIndex, result);
            currentIndex = i;
        }

        return result;
    }
}

原网站

版权声明
本文为[Lost summer]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/163/202206120202544970.html