leetcode 面試題 05.03. 翻轉數位

【題目】面試題 05.03. 翻轉數位

給定一個32位整數 num,你可以將一個數位從0變爲1。請編寫一個程序,找出你能夠獲得的最長的一串1的長度。

示例 1:

輸入: num = 1775(110111011112)
輸出: 8

示例 2:

輸入: num = 7(01112)
輸出: 4

【解題思路1】計數

class Solution {
    public int reverseBits(int num) {
        int bit = 32;
        int max = 0;
        int pre = 0;
        int after = 0;
        while(bit > 0){
            if((num & 1) == 0){ //當前位位0
                max = Math.max(max, pre + after + 1);
                pre = after;
                after = 0;
            }else{
                after++;
            }
            num >>= 1;
            bit--;
        }
        max = Math.max(max, pre + after + 1);
        return max;
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章