题解 | #求最大连续bit数#

求最大连续bit数

https://www.nowcoder.com/practice/4b1658fd8ffb4217bc3b7e85a38cfaf2

本题使用滑动窗口的思想,遍历二进制字符串,如果是1,ans = Math.max(ans,++sum);否则左边界要等于右边界,sum要置0.
import java.util.*;

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        while (sc.hasNext()) {
            int n = sc.nextInt();
            String tmp = Integer.toBinaryString(n);
            int ans = 0, sum = 0, L = tmp.length();
            int start = 0, end = 0;
            while (end < L) {
                int cur = tmp.charAt(end) - '0';
                if (cur == 1) {
                    sum ++;
                    ans = Math.max(ans, sum);
                } else {
                    sum = 0;
                    start = end;
                }
                end ++;
            }
            System.out.println(ans);
        }
    }
}


全部评论

相关推荐

自由水:笑死了,敢这么面试不敢让别人说
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务