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;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章