1069 The Black Hole of Numbers (20分)一定要仔细读题

①sscanf和sprintf的头文件是stdio.h,还可以方便的用于给数组开始插入n个0.
循环一次就结束了,总怀疑是自己strcmp和strcpy用得不对,其实是初始值没有处理好,看下边。最后一个if,如果二者不相等就让他两相等,那么while不就终止了吗?

#include<iostream>
#include<algorithm>
#include<stdio.h>
#include<string.h>
using namespace std;
bool cmp1(char a,char b)
{
    
    
    return a>b;
}
int main()
{
    
    
    char temp1[5]="aaaa",temp2[5]="bbbb",s1[5],s2[5];
    int a,b,sub;
    scanf("%s",s1);
    while(strcmp(temp1,temp2)!=0)
    {
    
    
        sort(s1,s1+4,cmp1);
        strcpy(s2,s1);
        sort(s2,s2+4);
        sscanf(s1,"%d",&a);
        sscanf(s2,"%d",&b);
        sub=a-b;
        sprintf(temp1,"%04d",sub);
        printf("%s - %s = %s\n",s1,s2,temp1);
        strcpy(s1,temp1);
        if(strcmp(temp1,temp2)!=0)
            strcpy(temp2,temp1);
    }
    return 0;
}

改成这样就好了,

#include<iostream>
#include<algorithm>
#include<stdio.h>
#include<string.h>
using namespace std;
bool cmp1(char a,char b)
{
    
    
    return a>b;
}
int main()
{
    
    
    char temp1[5]="aaaa",temp2[5]="bbbb",s1[5],s2[5];
    int a,b,sub;
    scanf("%s",s1);
    while(strcmp(temp1,temp2)!=0)
    {
    
    
        sort(s1,s1+4,cmp1);
        strcpy(s2,s1);
        sort(s2,s2+4);
        sscanf(s1,"%d",&a);
        sscanf(s2,"%d",&b);
        sub=a-b;
        sprintf(temp1,"%04d",sub);
        if(strcmp(temp1,temp2)!=0)
        {
    
    
            printf("%s - %s = %s\n",s1,s2,temp1);
            strcpy(s1,temp1);
            strcpy(temp2,temp1);
            temp1[0]='a';
        }
    }
    return 0;
}

不过仔细读题发现题目给出了最后要的数字6174,这样更好写,但有三个测试点超时,再度了一遍题,发现输入的是(0,10000),不一定是四位数,,所以在前面插入0就全部可以ac了
if (strlen(s1) < 4)
{
sscanf(s1,"%d",&a);
sprintf(s1,"%04d",a);
}

#include<iostream>
#include<algorithm>
#include<stdio.h>
#include<string.h>
using namespace std;
bool cmp1(char a,char b)
{
    
    
    return a>b;
}
int main()
{
    
    
    char temp1[5]="aaaa",s1[5],s2[5];
    int a,b,sub;
    scanf("%s",s1);
    while(strcmp(temp1,"6174")!=0)
    {
    
    
        sort(s1,s1+4,cmp1);
        strcpy(s2,s1);
        sort(s2,s2+4);
        if(strcmp(s1,s2)==0)
        {
    
    
             printf("%s - %s = 0000\n",s1,s2);return 0;
        }
        sscanf(s1,"%d",&a);
        sscanf(s2,"%d",&b);
        sub=a-b;
        sprintf(temp1,"%04d",sub);
        printf("%s - %s = %s\n",s1,s2,temp1);
        if(strcmp(temp1,"6174")!=0)
            strcpy(s1,temp1);
    }
    return 0;
}

这个方法好,要多熟悉熟悉algorithm下的函数

#include<iostream>
#include<string>
#include<algorithm>
using namespace std;
int main() {
    
    
	int val;
	string s,p;
	scanf("%d", &val);
	while (1) {
    
    
		s = to_string(val);
		if (s.length() < 4)s.insert(s.begin(), 4 - s.length(), '0');
		sort(s.begin(), s.end());
		p = s;
		reverse(p.begin(), p.end());
		printf("%04d - %04d = %04d\n", stoi(p),stoi(s), stoi(p) - stoi(s));
		val = stoi(p) - stoi(s);
		if (val == 0 || val == 6174)break;
	}
	return 0;
}