描述
将一个长度最多为30位数字的十进制非负整数转换为二进制数输出。
输入
多组数据,每行为一个长度不超过30位的十进制非负整数。
(注意是10进制数字的个数可能有30个,而非30bits的整数)
输出
每行输出对应的二进制数。
样例输入
0
1
3
8
样例输出
0
1
11
1000
分析问题:
将一个长度最多为30个数字的十进制非负整数转换为二进制数输出。这是大数问题,肯定需要用字符串来存储这个十进制数,转化出来的二进制也需要用字符串来存储。和小数的转化一样,不断取2的模,然后除2。
思路:
字符串模2除2
可以优化程序。//冰非寒(binfeihan@126.com) //252kB 30ms 1096 B G++ #include <iostream> #include <string> using namespace std; const int N = 31; //class: Binary typedef class Binary{ public: void dec2bin(string s); void print(); private: string BinaryNum; }Binary; //convert decimal to Binary void Binary::dec2bin(string s){ int sum(0),j(0); string bin; int an[N]={0}; //assign to an for(int i(s.length() - 1);i >= 0;-- i){ an[j] = s[i] - '0'; sum += an[j]; ++ j; } //calculate the Binary number while(1){ char ch = an[0] % 2 + '0'; bin.insert(bin.length(),1,ch); sum = 0; for(int i(j - 1);i >= 0;-- i){ if(i > 0){ an[i - 1] += an[i] % 2 * 10; } an[i] /= 2; sum += an[i]; } if(sum == 0){ break; } } //reverse the Binary number and assign for(int i(bin.length() - 1);i >= 0;-- i){ this->BinaryNum.insert(this->BinaryNum.length(),1,bin[i]); } } //print void Binary::print(){ //print the Binary number cout<<this->BinaryNum<<endl; } //main function int main(){ string dec; while(cin>>dec){ Binary b; b.dec2bin(dec); b.print(); } return 0; }
将一个长度最多为30位数字的十进制非负整数转换为二进制数输出。
输入
多组数据,每行为一个长度不超过30位的十进制非负整数。
(注意是10进制数字的个数可能有30个,而非30bits的整数)
输出
每行输出对应的二进制数。
样例输入
0
1
3
8
样例输出
0
1
11
1000
分析问题:
将一个长度最多为30个数字的十进制非负整数转换为二进制数输出。这是大数问题,肯定需要用字符串来存储这个十进制数,转化出来的二进制也需要用字符串来存储。和小数的转化一样,不断取2的模,然后除2。
思路:
字符串模2除2
可以优化程序。//冰非寒(binfeihan@126.com) //252kB 30ms 1096 B G++ #include <iostream> #include <string> using namespace std; const int N = 31; //class: Binary typedef class Binary{ public: void dec2bin(string s); void print(); private: string BinaryNum; }Binary; //convert decimal to Binary void Binary::dec2bin(string s){ int sum(0),j(0); string bin; int an[N]={0}; //assign to an for(int i(s.length() - 1);i >= 0;-- i){ an[j] = s[i] - '0'; sum += an[j]; ++ j; } //calculate the Binary number while(1){ char ch = an[0] % 2 + '0'; bin.insert(bin.length(),1,ch); sum = 0; for(int i(j - 1);i >= 0;-- i){ if(i > 0){ an[i - 1] += an[i] % 2 * 10; } an[i] /= 2; sum += an[i]; } if(sum == 0){ break; } } //reverse the Binary number and assign for(int i(bin.length() - 1);i >= 0;-- i){ this->BinaryNum.insert(this->BinaryNum.length(),1,bin[i]); } } //print void Binary::print(){ //print the Binary number cout<<this->BinaryNum<<endl; } //main function int main(){ string dec; while(cin>>dec){ Binary b; b.dec2bin(dec); b.print(); } return 0; }
改进后的代码:
时间分析
1.cout,cin读写比scanf,printf慢
2.调用string函数比直接操作char型字符数组占时间