Decimal integer conversion
时间限制:
1000 ms | 内存限制:
65535 KB
难度:
2
-
描述
- XiaoMing likes mathematics, and he is just learning how to convert numbers between different bases , but he keeps making errors since he is only 6 years old. Whenever XiaoMing converts a number to a new base and writes down the result, he always writes one of the digits wrong. For example , if he converts the number 14 into binary (i.e., base 2), the correct result should be "1110", but he might instead write down "0110" or "1111". XiaoMing never accidentally adds or deletes digits, so he might write down a number with a leading digit of " 0" if this is the digit she gets wrong. Given XiaoMing 's output when converting a number N into base 2 and base 3, please determine the correct original value of N (in base 10). (N<=10^10) You can assume N is at most 1 billion, and that there is a unique solution for N.
-
输入
-
The first line of the input contains one integers T, which is the nember of test cases (1<=T<=8)
Each test case specifies:
* Line 1: The base-2 representation of N , with one digit written incorrectly.
* Line 2: The base-3 representation of N , with one digit written incorrectly.
输出
-
For each test case generate a single line containing a single integer , the correct value of N
样例输入
-
1 1010 212
样例输出
-
14
思路:模拟,把二进制,三进制每一位都换一下求出结果,保存进数组,比较二个数组中有没有相同的值,有的话就是N
#include<string.h>
#include<string>
#include<vector>
#include<math.h>
#include<stdio.h>
#include<iostream>
#include<algorithm>
using namespace std;
vector<int>v1;//存放2进制结果
vector<int>v2;//存放3进制结果
int fun(int a,int n)
{//这里自己写了快速幂,也可以用pow()
int sum=1;
while(n>0){
if(n&1)
sum=sum*a;
a=a*a;
n>>=1;
}
return sum;
}
int sum(string s,int c)
{//求数
int ans=0;
int len=s.length();
for(int i=0;i<len;i++)
{
ans+=(s[i]-'0')*fun(c,len-1-i);
}
return ans;
}
int main()
{
int t;
scanf("%d",&t);
string s1,s2;
while(t--)
{
cin>>s1>>s2;
string s;
int l1=s1.length();
int l2=s2.length();
int a,b,c,d;
for(int i=0;i<l1;i++)
{
if(s1[i]=='0')
{
s=s1;
s[i]=s1[i]+1;
int num=sum(s,2);
v1.push_back(num);
}
else
{
s=s1;
s[i]=s1[i]-1;
int num=sum(s,2);
v1.push_back(num);
}
}
for(int i=0;i<l2;i++)
{
if(s2[i]=='0')
{
s=s2;
s[i]=s2[i]+1;
int num=sum(s,3);
v2.push_back(num);
s=s2;
s[i]=s2[i]+2;
num=sum(s,3);
v2.push_back(num);
}
else if(s2[i]=='1')
{
s=s2;
s[i]=s2[i]+1;
int num=sum(s,3);
v2.push_back(num);
s=s2;
s[i]=s2[i]-1;
num=sum(s,3);
v2.push_back(num);
}
else if(s2[i]=='2')
{
s=s2;
s[i]=s2[i]-1;
int num=sum(s,3);
v2.push_back(num);
s=s2;
s[i]=s2[i]-2;
num=sum(s,3);
v2.push_back(num);
}
}
int ans;
for(int i=0;i<v1.size();i++)
{
for(int j=0;j<v2.size();j++)
if(v1[i]==v2[j])
{
ans=v1[i];
break;
}
}
printf("%d\n",ans);
v1.clear();//每次清空
v2.clear();
}
return 0;
}