问题描述
做这道题的时候,我的开始思路是首先接收四个输入的字符,然后对数组顺序和逆序排序,再对结果进行转换计算差值,将差值转换成字符串进行下一循环。但是在提交时2、3、4测试点不通过。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
| int main() { char a[4]; cin>>a[0]>>a[1]>>a[2]>>a[3]; a[4] = 0; int result = -1; while (result!=0&&result!=6174){ int first,second; sort(a,a+4, compare_first); first = atoi(a); cout<<a<<" - "; sort(a,a+4, compare_second); second = atoi(a); cout<<a<<" = "; a[0] = a[1] = a[2] = a[3] = '0'; result = first - second; if (result == 0) cout<<"0000"; else if (result<10) cout<<"000"<<result<<endl; else if (result<100) cout<<"00"<<result<<endl; else if (result<1000) cout<<"0"<<result<<endl; else cout<<result<<endl; int temp = result; int i =0; while (i <4){ a[i++] = '0' + temp % 10; temp /= 10; } a[4] = 0; } return 0; }
|
问题分析
根据问题描述,输入格式是(0~10^4)的正整数,而我接收的是四个字符,当输入小于四位时,后面的几个就会接收不到数据,使后面计算出现问题。
解决方法
输入接收整型数字后,转换成字符串就可以解决这一问题。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
| int main() { char a[4]; int n; cin >> n; int2char(a,n); int result = -1; while (result!=0&&result!=6174){ int first,second; sort(a,a+4, compare_first); first = atoi(a); cout<<a<<" - "; sort(a,a+4, compare_second); second = atoi(a); cout<<a<<" = "; a[0] = a[1] = a[2] = a[3] = '0'; result = first - second; if (result == 0) cout<<"0000"; else if (result<10) cout<<"000"<<result<<endl; else if (result<100) cout<<"00"<<result<<endl; else if (result<1000) cout<<"0"<<result<<endl; else cout<<result<<endl; int2char(a,result); } return 0; }
|
tips
1、itoa()函数不能在评测系统中使用,错误提示‘itoa’ was not declared in this scope
2、字符串应以’/0’(ASCII码为0)作为结束符