跳转至

3827. 统计单比特整数

题目描述

给你一个整数 n

如果一个整数的二进制表示中所有位都相同,则称其为 单比特数Monobit)。

返回范围[0, n](包括两端)内 单比特数 的个数。

 

示例 1:

输入: n = 1

输出: 2

解释:

  • 范围[0, 1]内的整数对应的二进制表示为"0""1"
  • 每个表示都由相同的位组成,因此答案是2。

示例 2:

输入: n = 4

输出: 3

解释:

  • 范围[0, 4]内的整数对应的二进制表示为"0""1""10""11""100"
  • 只有013满足单比特条件。因此答案是3。

 

提示:

  • 0 <= n <= 1000

解法

方法一

1
2
3
4
5
6
7
8
9
class Solution:
    def countMonobit(self, n: int) -> int:
        ans = x = 1
        i = 1
        while x <= n:
            ans += 1
            x += (1 << i)
            i += 1
        return ans
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
class Solution {
    public int countMonobit(int n) {
        int ans = 1;
        for (int i = 1, x = 1; x <= n; ++i) {
            ++ans;
            x += (1 << i);
        }
        return ans;
    }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
class Solution {
public:
    int countMonobit(int n) {
        int ans = 1;
        for (int i = 1, x = 1; x <= n; ++i) {
            ++ans;
            x += (1 << i);
        }
        return ans;
    }
};
1
2
3
4
5
6
7
8
func countMonobit(n int) (ans int) {
    ans = 1
    for i, x := 1, 1; x <= n; i++ {
        ans++
        x += (1 << i)
    }
    return
}
1
2
3
4
5
6
7
8
function countMonobit(n: number): number {
    let ans = 1;
    for (let i = 1, x = 1; x <= n; ++i) {
        ++ans;
        x += 1 << i;
    }
    return ans;
}

评论