TJU Bitwise Reverse

13 篇文章 0 订阅
Professor Robby invents a powerful encryption method, but he is too lazy to implement it. So he turns to you for help.

In fact, the encryption method is only applied to positive integers. At first, we express the number as binary code, that is, a string only contain '0' and '1', and the first digit can't be '0'. Then we reverse the string. And the last step, we calculate the reversed binary code and express it in decimal again.

For example, we want to encrypt the number 14, we express it as 1110, after reversing it we get 0111, and (0111)2 = 7. So we get 7.

Input

There is only one line for each test case, containing the positive integer to be encrypted. You can assume the number is not more than 10 6 .

The input is terminated with a zero.

Output

Output one line for each test case, indicating the number after encryption.

Sample Input

5
6
14
0

Sample Output

5
3
7
 
 
题意概述:将给定整数用2进制表示,然后将其逆序。例如:14用2进制表示为1110,逆序后为0111. 将逆序后的数转换为十进制数。

解题思路:给定一个整数,对其进行除二取余,将每次得到的余数用后插法插入deque容器中,然后将存在deque中的数转化为十进制即可。例如:若deque中的序列为0111,则结果为0*8+1*4+1*2+1=7.

源代码:

#include<iostream>
#include<deque>
using namespace std;
int main()
{
    unsigned N;   //之所以用unsigned,是因为题目中说明为非负整数 
    deque<unsigned> Set; //定义动态数组 
    while(cin>>N&&N)
    {
         int len=0;      //存储动态数组的长度 
         while(N)
         {
             Set.push_back(N%2);
             N/=2;
             ++len;
         }
         
         unsigned result=0;   
         deque<unsigned>::iterator pos;
         pos=Set.begin();
         for(int i=1;i<=len&&pos!=Set.end();++i,++pos)
         {
             if(i<len)result=(result+*pos)*2;
             else result+=*pos;
         }
         cout<<result<<endl;
         Set.clear();           //清空容器 
    }
    return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值