Pat1019代码
这个题目是遇到的最郁闷的题目,我的代码居然一个case都没通过,下面我把AC代码和我的代码都贴出来,如果有谁知道我的代码为什么错了,请说出来,谢谢。。。
AC代码:
#include <iostream> #include <sstream> using namespace std; int power(int a, int n) { int res = 1; for (int i = 0; i < n; ++i) { res *= a; } return res; } int compare(const void * a, const void * b) { return *(int*)a - *(int*) b; } int nonIncrese(int n) { int digits[4]; digits[0] = n % 10; digits[1] = n / 10 % 10; digits[2] = n / 100 % 10; digits[3] = n / 1000; qsort(digits, 4, sizeof(int), compare); int res = 0; for (int i = 0; i < 4; ++i) { res += digits[i] * power(10, i); } return res; } int nonDecrese(int n) { int digits[4]; digits[0] = n % 10; digits[1] = n / 10 % 10; digits[2] = n / 100 % 10; digits[3] = n / 1000; qsort(digits, 4, sizeof(int), compare); int res = 0; for (int i = 0; i < 4; ++i) { res += digits[3-i] * power(10, i); } return res; } string toString(int n) { string sn = static_cast<ostringstream*>( &(ostringstream() << n) )->str(); if (n < 10){ string s0 = "000"; return s0.append(sn); } if (n < 100){ string s0 = "00"; return s0.append(sn); } if (n < 1000) { string s0 = "0"; return s0.append(sn); } return sn; } int main() { int N; cin >> N; // N >= 1000, N <= 9999 if (N % 1111 == 0) { cout << N << " - " << N << " = " << "0000" << endl; } else if (N == 6174) { cout << "7641 - 1467 = 6174" << endl; } else{ int n = N; while (n != 6174){ cout << toString(nonIncrese(n)) << " - " << toString(nonDecrese(n)) << " = " << toString(nonIncrese(n) - nonDecrese(n)) << endl; n = nonIncrese(n) - nonDecrese(n); } } return 0; }
我的代码:
#include<stdio.h> int main(int argc,char *argv[]) { int n,temp; int max,min; int i,j; int arr[4]; scanf("%d",&n); do { max=0; min=0; for(i=0;i<4;i++) { arr[i]=n%10; n=n/10; } for(i=1;i<4;i++) for(j=0;j<4-i;j++) { if(arr[j]>arr[j+1]) { temp=arr[j]; arr[j]=arr[j+1]; arr[j+1]=temp; } } for(i=0;i<4;i++) min=min*10+arr[i]; for(j=3;j>=0;j--) max=max*10+arr[j]; n=max-min; printf("%.4d - %.4d= %.4d\n",max,min,n); }while(n!=6174&&n!=0); return 0; }
求高手指点迷津啊。。。