C++程序练习-3249:进制转换-30位十进制转二进制数-优化

描述
将一个长度最多为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型字符数组占时间

//冰非寒(binfeihan@126.com) //256kB 0ms 1364 B G++ #include <stdio.h> #include <string.h> const int N = 31; const int M = 200; //class: Binary typedef class Binary{ public: void dec2bin(char s[]); void print(); private: char BinaryNum[M]; }Binary; //convert decimal to Binary void Binary::dec2bin(char s[]){ int i(0),sum(0),j(0),k(0),t(1),p(0); char ch; char bin[M]; int an[N]={0}; //assign to an for(i = strlen(s) - 1;i >= 0;-- i){ if(k < 4){ an[j] = an[j] + (s[i] - '0') * t; t *= 10; k ++; } if(k == 4){ k = 0; ++ j; t = 1; continue; } } if(k != 0){ ++ j; } //calculate the Binary number k = 0; while(1){ ch = an[0] % 2 + '0'; bin[p ++] = ch; sum = 0; for(i = j - 1;i >= 0;-- i){ if(i != 0){ an[i - 1] += an[i] % 2 * 10000; } an[i] /= 2; sum += an[i]; if(k == 0 && an[i] > 0){ t = i + 1; k = 1; } } if(sum == 0){ break; } j = t; k = 0; } //reverse the Binary number and assign j = 0; for(i = p - 1;i >= 0;-- i){ this->BinaryNum[j ++] = bin[i]; } this->BinaryNum[j] = '\0'; } //print void Binary::print(){ //print the Binary number printf("%s\n",this->BinaryNum); } //main function int main(){ char dec[M]; while(scanf("%s",dec) == 1){ Binary b; b.dec2bin(dec); b.print(); } return 0; }
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值