题目描述
Bessie the cow is just learning how to convert numbers between different bases, but she keeps making errors since she cannot easily hold a pen between her two front hooves.
Whenever Bessie converts a number to a new base and writes down the result, she always writes one of the digits wrong. For example, if she converts the number 14 into binary (i.e., base 2), the correct result should be “1110”, but she might instead write down “0110” or “1111”. Bessie never accidentally adds or deletes digits, so she might write down a number with a leading digit of “0” if this is the digit she gets wrong. Given
Bessie’s output when converting a number N into base 2 and base 3, please determine the correct original value of N (in base 10). You can assume N is at most 1 billion, and that there is a unique solution for N.
Please feel welcome to consult any on-line reference you wish regarding base-2 and base-3 numbers, if these concepts are new to you.
输入描述:
- 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.
输出描述:
- Line 1: The correct value of N.
测试输入
1010
212
测试输出
2
解题说明
解题思路
这道题是说母牛会将一个十进制整数的二进制和三进制数各写错一位,然后让你反推出这个十进制整数。N的范围是在1亿。
其实这道题没有涉及到太多的算法,我的思路是先判断二进制,因为二进制写错最多是1变0或者0变1,那这样我就循环二进制的每一位,将其改改变后转换成long long长整数后,再转换成二三进制后和输入的三进制进行判断,如果只差一位,那么就是需要求的解。
因为比较大,用long long
#include<iostream>
#include<cstring>
#include<algorithm>
#include<cmath>
using namespace std;
long long changeToNum(string str){ //将二进制转换成整数
long long ans=0;
long long len = str.size();
for(int i=0;i<len;i++){
ans+=(str[i]-'0')*pow(2,len-i-1);
}
return ans;
}
string changeToString (long long num){ //将整数转换成三进制,用于判断是否
int k;
string str,ans;
while(num){
k=num%3;
str.push_back((k+'0'));
num/=3;
}
long long len = str.size();
for(int i=len-1;i>=0;i--){
ans.push_back(str[i]);
}
return ans;
}
int main()
{
string base2,base3;
cin>>base2>>base3;
if(base2[0]=='0'){
base2[0]='1';
cout<<changeToNum(base2);
return 0;
}
long long maxnum,minnum;
long len2=base2.size();
long len3=base3.size();
int l=0;
string x,t;
for(int i=1;i<len2;i++){
t= base2;
t[i]=abs((t[i]-'0')-1)+'0';
minnum = changeToNum(t);
x=changeToString(minnum);
l=0;
//cout<<x<<endl;
for(int j=0;j<len3;j++){
if(x[j]!=base3[j]){
l++;
}
}
if(l==1&&x.size()==len3){
cout<<minnum<<endl;
break;
}
}
}
大致这样叭有问题请指教
题目来源
链接:https://ac.nowcoder.com/acm/contest/7156/J
来源:牛客网