Maximum number of rearrangements

Topic: Enter a positive integer within 1000 (not including 1000), first fill it up into three numbers (if it is a two-digit or one-digit number, then add 0 in front), and then put the three numbers in a different order Arrange into a set of data, and output the largest number in the arrangement.
For example:
if you enter 249, you can re-eject 429, 249, 924, 942, etc., the largest of which should be 942, so it should output 942;
if you enter 14, add 0 to the front to get 014, and then you can re-eject 041, 140, 410 and so on, the largest of which should be 410, so 410 should be output.
Rearrange the three digits of the input positive integers within 1000 (if it is two digits or one digit, then add 0 in front) to get the largest number and output.
Test input 1: 5
Expected output 1: 500
Test input 2: 185
Expected output 2: 851

The starting code is as follows:

#include <stdio.h>
#include <iostream>
using namespace std;
int main()
{
    
    
    int n, m;
	while(scanf("%d",&n) !=EOF){
    
    
	    if(0<n && n<=9){
    
    
	        m=n*100;
	    }
	    else if(10<=n && n<=99){
    
    
	        int p=n%10;
	        int q=n/10;
	        if(p>q)
	            m=p*100+q*10;
	        else
	            m=q*100+p*10;
	    }
	    else{
    
    
	        int q=n/100;
	        int w=(n-q*100)/10;
	        int e=n%10; 
	        if(q>w && w>e)
	            m=q*100+w*10+e;
	        else if(q>e && w<e)
	            m=q*100+e*10+w;
	        else if(w>q && q>e)
	            m=w*100+q*10+e;
	        else if(w>e && q<e)
	            m=w*100+e*10+q;
	        else if(e>w && w>q)
	            m=e*100+w*10+q;
	        else
	            m=e*100+q*10+w;
	    }
    	cout << m << endl;
	}
    return 0;
}

The test always failed, and later found out:

//输入:977
//输出:797

When something went wrong, I realized that I had forgotten the condition of equality. Just add the equal sign in the comparison process:

#include <stdio.h>
#include <iostream>
using namespace std;
int main()
{
    
    
    int n, m;
	while(scanf("%d",&n) !=EOF){
    
    
	    if(0<n && n<=9){
    
    
	        m=n*100;//一位数一定这样最大
	    }
	    else if(10<=n && n<=99){
    
    
	        int p=n%10;
	        int q=n/10;
	        if(p>=q)
	            m=p*100+q*10;
	        else
	            m=q*100+p*10;
	    }//二位数时只需比较一次个位数与十位数
	    else{
    
    
	        int q=n/100;
	        int w=(n-q*100)/10;
	        int e=n%10; 
	        if(q>=w && w>=e)
	            m=q*100+w*10+e;
	        else if(q>=e && w<=e)
	            m=q*100+e*10+w;
	        else if(w>=q && q>=e)
	            m=w*100+q*10+e;
	        else if(w>=e && q<=e)
	            m=w*100+e*10+q;
	        else if(e>=w && w>=q)
	            m=e*100+w*10+q;
	        else
	            m=e*100+q*10+w;
	    }//三位数比较六次,注意是>= 或 <= 而不是 > 或 <
    	cout << m << endl;
	}
    return 0;
}

Guess you like

Origin blog.csdn.net/interestingddd/article/details/113841687