45-題目1138:進制轉換

http://ac.jobdu.com/problem.php?pid=1138

題目描述:

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

輸入:

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

輸出:

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

我不懂大數據的進制轉換,不知道到底怎麼算,這個核心是別人的AC代碼:

#include<iostream>
#include<algorithm>
#include<iomanip>
#include<fstream>
using namespace std;

int main()
{
	int num[32], length;
	char n[32];
	ifstream cin("data.txt");
	while (cin >> n)
	{
		for (length = 0; n[length]; length++)
			num[length] = n[length] - '0';
		int i = 0, j, c, len_res = 0,temp;
		char res[200];

		while (i < length)
		{
			res[len_res++] = num[length - 1] % 2 + '0';
			//這裏是轉化爲2進制,只用最後一位來除2餘數就可以了,其他高位對除2餘數不影響,因爲從高位借過一位來總是能被2整除,
			c = 0;//借位
			for (j = i; j < length; j++)
			{
				temp = num[j];
				num[j] = (num[j] + c) / 2;
				if (temp & 1) //當這一位是奇數的時候表示不能整除2,要借位了
					c = 10;
				else
					c = 0;
			}
			if (num[i] == 0)//可能前幾次不爲0,再循環
				i++;
		}

		for (i = len_res - 1; i >= 0; i--)//逆向輸出
			cout << res[i];	
		cout << endl;
	}//end of while
	system("pause");
	return 0;
}

java的BigInteger類實在是很好用,簡直就是作弊啊!但是我不會java。。。

AC: 【1138】進制轉換

import java.util.*;
import java.math.*;

public class Main {

public static void main(String args[]){

Scanner cin=new Scanner(System.in);

BigInteger a;

while(cin.hasNext()){

a=cin.nextBigInteger();

System.out.println(a.toString(2));

}

}
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章