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;
}