2023-05-20 Analysis of Youth Software Programming (C Language) Grade Examination Paper (Level 5)

2023-05-20 Adolescent Software Programming (C Language) Grade Examination Paper (Level 5) Analysis
T1, Problem Solving
Given a positive integer N, find the smallest M that is greater than N and has the same number in the binary representation of M and N 1.
For example, if N is given as 78, the binary representation is 1001110, which contains 4 1s, then the smallest number that is larger than N and contains only 4 1s in the binary representation is 83, and its binary representation is 1010011, so 83 is Answer.
Time limit: 1000
Memory limit: 65536
input
Input several lines, each line has a number N (1 ≤ N ≤ 1000000), if this line is 0, it means the input is over.
Output
For each N, output the corresponding M.
Sample input
1
2
3
4
78
0
Sample output
2
4
5
8
83

// 样例代码  枚举
using namespace std;
int n;  // 定义变量 n
int tj(int x) {
    int ans = 0;  // 定义变量 ans
    while (x) {  // 当 x 不为0循环执行
        if (x &)
            ans++;  // 如果 x 的最低位为1,则将 ans 加1
        x >>= 1;  // 将 x 右移1位,即将 x 的二进制表示向右移动一位
    }
    return ans;  // 返回 ans
}
int main() {
    whi

Guess you like

Origin blog.csdn.net/lybc2019/article/details/131162700