C++程序练习-3871:Binary System-打表

描述
Usually we use number in the decimal system, for it is so convenient for us to remember and calculate.

But it is not the same in the computer world where numbers are always stored in the binary system. For example, the number 21 in decimal can be presented as (21)10 = (10101)2 = 24+22+20. It is the sum of the power of 2. Note that in the first item, the power is 4, then the number 4 can be presented as (4)10 = (100)2=22, so (21)10 =22^2 +22 +20 , and it is much more convenient for computer to display as 21=2(2(2))+2(2)+2(0). Every positive integer can be written in this form following these principles:
1. Number 1 is presented as 2(0), while number 2 is presented as 2. Then other numbers must be combined by these two basic numbers;
2. The powers of 2 are always sorted in descending order.

输入
Each line of the Input is the number n (0 < n < 1000000) in the binary system. Input file is ended with -1.

输出
For each case, you should only export the equation as the sample output. Be careful of the space before and after the equal sign. And there mustn't be any more space in your output.

样例输入
8
21
1315
-1
样例输出
8 = 2(2+2(0))
21 = 2(2(2))+2(2)+2(0)
1315 = 2(2(2+2(0))+2)+2(2(2+2(0)))+2(2(2)+2(0))+2+2(0)


思路:
最初想按步就班去计算,但后面想想数据并不是很大,可以尝试打表。
按照这一思路走下去,发现不是很复杂其有点简单。
最终成功的AC了这个问题。
但是,这应该不是真正的解法,值得再次思考。????

//http://poj.grids.cn/practice/3871/ //菜鸟打表AC,有没有TX有其他解法,请求GX学习。 //好好学习,day day up。 //Accepted 252kB 0ms 1071 B G++ #include <iostream> #include <string> using namespace std; const string map[17]={ "0", "2(0)", "2", "2+2(0)", "2(2)", "2(2)+2(0)", "2(2)+2", "2(2)+2+2(0)", "2(2+2(0))", "2(2+2(0))+2(0)", "2(2+2(0))+2", "2(2+2(0))+2+2(0)", "2(2+2(0))+2(2)", "2(2+2(0))+2(2)+2(0)", "2(2+2(0))+2(2)+2", "2(2+2(0))+2(2)+2+2(0)", "2(2(2))"}; int main(){ int i,n,nval,plus,base[32]; base[0] = 1; for(i = 1;i < 32;i ++){ base[i] = base[i - 1] * 2; } /* for(i = 0;i < 31;i ++){ std::cout<<base[i]<<std::endl; } */ while(std::cin>>n && n != -1){ nval = n; plus = 0; std::cout<<n<<" = "; for(i = 30;i >= 0;i --){ //std::cout<<nval<<" "<<base[i]<<std::endl; if(nval >= base[i]){ if(plus == 1){ std::cout<<"+"; } nval -= base[i]; if(i > 16){ std::cout<<"2("<<map[16]; std::cout<<"+"<<map[i - 16]<<")"; }else{ if(base[i] == 2){ std::cout<<"2"; }else{ std::cout<<"2("<<map[i]<<")"; } } plus = 1; } } std::cout<<std::endl; } return 0; }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值