注意测试点可能为6174,已经循环结束条件应为(n != 6174 && n != 0)
用stl和普通方法各写了一次。
普通方法:
#include <iostream> #include<string> #include<stdio.h> #include<algorithm> using namespace std; bool cmp(char a, char b) { return a > b; } int main() { char ch[5]; int n; cin.getline(ch, 5); sscanf(ch, "%d", &n); if (n == 6174) { cout << "7641 - 1467 = 6174"; return 0; } while (n != 6174&&n!=0) { int i; for (i = 0; i < 4; i++) if (ch[i]== '\0') break; fill(ch + i, ch + 4, '0');//说明不够4位数,把不够的位数用0补足。 ch[4] = '\0';//一定要加上‘\0’ int a, b; sort(ch, ch + 4, cmp); cout << ch;//打印递减的ch sscanf(ch, "%d", &a);//字符串转整型。 sort(ch, ch + 4); cout << " - " << ch << " = ";//打印递增的ch sscanf(ch, "%d", &b); n = a - b; printf("%04d\n", n); sprintf(ch, "%d", n); } }
stl方法:
#include <iostream> #include<string> #include<stdio.h> #include<algorithm> using namespace std; bool cmp(char a, char b) { return a > b; } int main() { string ch; getline(cin, ch); if (ch == "6174") { cout << "7641 - 1467 = 6174"; return 0; } while (ch != "6174"&&ch!="0") { int a,b,n; if(ch.size()<4) ch.insert(0,4-ch.size(),'0'); sort(ch.begin(), ch.end(), cmp); cout << ch;//打印递减的ch a=stoi(ch);//字符串转十进制整型。 sort(ch.begin(), ch.end()); cout << " - " << ch << " = ";//打印递增的ch b=stoi(ch);//字符串转十进制整型 n = a - b; printf("%04d\n", n); ch=to_string(n);//整型转字符串。 } }