九度 題目1138:進制轉換

九度 題目1138:進制轉換

原題OJ鏈接:http://ac.jobdu.com/problem.php?pid=1138

題目描述:

將一個長度最多爲30位數字的十進制非負整數轉換爲二進制數輸出。

輸入:

多組數據,每行爲一個長度不超過30位的十進制非負整數。
(注意是10進制數字的個數可能有30個,而非30bits的整數)

輸出:

每行輸出對應的二進制數。

樣例輸入:

0
1
3
8

樣例輸出:

0
1
11
1000

解題思路:

30位的十進制數超出了long long int的範圍,
long long的最大值:9223372036854775807
long long的最小值:-9223372036854775808
unsigned long long的最大值:1844674407370955161

思路分析參考的這位大神的博客:http://blog.csdn.net/wzy_1988/article/details/8640266

源代碼:

#include<iostream>
#include<cstdio> 
#include<cstring>
using namespace std;
int main(){
    char str[30];
    while(scanf("%s",str)!=EOF){
        int sum=1;
        int N[105];
        int i,j=0;
        while(sum){
            sum=0;
            int len=strlen(str);
            for(i=0;i<len;i++){
                int d=(str[i]-'0')%2;
                int x=(str[i]-'0')/2;
                sum=sum+x;
                if(i==len-1){
                    N[j]=d;
                    j++;
                }
                else{
                    str[i+1] += d*10;
                }
                str[i]=x+'0';
            }
        }
        for(i=j-1;i>=0;i--){
            cout<<N[i];
        }
        cout<<endl;
    }
    return 0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章