每日刷题41

资源限制
内存限制:256.0MB C/C++时间限制:1.0s Java时间限制:3.0s Python时间限制:5.0s
  编写一个程序,输入一个4位的自然数,将组成该数的各位数字重新排列,形成一个最大数和一个最小数,之后用最大数减去最小数,得到一个新的自然数,把这个数打印出来。然后对于这个新的自然数,重复上述步骤,直到该自然数的值不再发生变化。例如,假设用户输入的自然数为1001,那么由它所形成的最大数为1100,最小数为11,因此新的自然数为1089。对于1089,由它形成的最大数为9810,最小数为189,因此新的自然数为9621。9621的最大数为9621,最小数为1269,结果为8352,。8352的最大数为8532,最小数为2358,结果为6174。6174的最大数为7641,最小数为1467,结果仍为6174,因此程序结束。
输入:
  1001
输出:
  6174
解答:

#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
ll n,maxtemp,mintemp,maxnum,minnum,resultnum;
ll ap[10],ap1[10];
int getweishu(ll n){
    
    
    int counts=0;
    while(n){
    
    
        n/=10;
        counts++;
    }
    return counts;
}
void insertsuzhu(ll n,ll *ap,ll length){
    
    
    for(int i =0;i<length;i++){
    
    
        int temp1 = n%10;
        ap[length-1-i] = temp1;
        n/=10;
    }
}
int findmax(ll *ap,int start,int length){
    
    
    int max=start;
    for(int i =start;i<length;i++){
    
    
        if(ap[i]>ap[max])
            max= i;
    }
    return max;
}
int findmin(ll *ap,int start,int length){
    
    
    int min=start;
    for(int i =start;i<length;i++){
    
    
        if(ap[i]<ap[min])
            min= i;
    }
    return min;
}
void transformtoap1(ll *a, ll *n){
    
    
    ll i,temp;
    for(i =0;i<*n;i++){
    
    
        if(a[i]==0)
        continue;
        else
        break;
    }
    temp = i;
    for(ll j = 0;j<*n;j++){
    
    
        a[j] = a[i++];
    }
    *n = *n - temp;
}
int main(){
    
    

    cin >> n;
    while(1){
    
    
    maxtemp = getweishu(n);
    mintemp = getweishu(n);
    insertsuzhu(n,ap,maxtemp);
    for(int i =0;i<maxtemp;i++)
        ap1[i] = ap[i];

    
    for(int i = 0;i<maxtemp;i++){
    
    
        int max = findmax(ap,i,maxtemp);
        // cout<<max;
        if(max!=i){
    
    
            ll temp2 = ap[max];
            ap[max] = ap[i];
            ap[i] = temp2;
        }
    }
    //  for(int i =0;i<maxtemp;i++)
    // cout<<ap[i];
    // cout<<endl;
    maxnum = 0;
    for(int i = 0;i<maxtemp;i++){
    
    
        maxnum += ap[i]*pow(10,maxtemp-i-1);
    }
    // cout<<maxnum;
    // cout<<endl;
    for(int i = 0;i<mintemp;i++){
    
    
        int min = findmin(ap1,i,mintemp);
        if(min!=i){
    
    
            ll temp2 = ap1[min];
            ap1[min] = ap1[i];
            ap1[i] = temp2;
        }
    }
    transformtoap1(ap1, &mintemp);
    // for(int i =0;i<mintemp;i++)
    // cout<<ap1[i];
    // cout<<endl;
    minnum = 0;
    for(int i = 0;i<mintemp;i++){
    
    
        minnum += ap1[i]*pow(10,mintemp-i-1);
    }
    // cout<<minnum<<endl;
    ll tempn = maxnum - minnum;
    if(tempn == n)
      break;
     n = tempn;
    }
   cout<<n;
   return 0;
   
}

猜你喜欢

转载自blog.csdn.net/weixin_47988292/article/details/130112413