POJ--2453--An Easy Problem

题目描述:
As we known, data stored in the computers is in binary form. The problem we discuss now is about the positive integers and its binary form.

Given a positive integer I, you task is to find out an integer J, which is the minimum integer greater than I, and the number of '1’s in whose binary form is the same as that in the binary form of I.

For example, if “78” is given, we can write out its binary form, “1001110”. This binary form has 4 '1’s. The minimum integer, which is greater than “1001110” and also contains 4 '1’s, is “1010011”, i.e. “83”, so you should output “83”.
输入描述:
One integer per line, which is I (1 <= I <= 1000000).

A line containing a number “0” terminates input, and this line need not be processed.
输出描述:
One integer per line, which is J.
输入:
1
2
3
4
78
0
输出:
2
4
5
8
83
题意:
给定一个正整数 I,你需要找出一个整数 J,它是大于 I 且其二进制形式中’1’的个数与 I 的二进制形式中’1’的个数相同的最小整数。
例如,对于整数“78”,其二进制形式为“1001110”,其中有 4 个’1’。大于“1001110”且包含 4 个’1’的最小整数为“1010011”,即“83”,因此应输出“83”。
题解
直接暴力,也可以贪心
代码:

#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
using namespace std;

int b[50];

int getbit(int n){
    int ans,t;
    memset(b,0,sizeof(b));
    for(int i = 0;;i ++){
        if(n == 1){
            t = i;
            b[i] = 1;
            break;
        }
        b[i] = n % 2;
        n /= 2;
    }
    ans = 0;
    for(int i = 0;i <= t; i ++){
        if(b[i] == 1) ans ++;
    }
    return ans;
}


int main(){
    int n;
    while(scanf("%d",&n)!=EOF){
        if(n == 0) break;
        int num1 = getbit(n);
        while(1){
            n ++;
            int num2 = getbit(n);
            if(num1 == num2){
                break;
            }
        }
        printf("%d\n",n);
    }
    return 0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章