UVa 11371 - Number Theory for Newbies Solution

#include <iostream>
#include <vector>
using namespace std;
int main(){
    ios::sync_with_stdio(0);
    long long n;
    while(cin>>n){
        vector<int> a(10),b(10);
        while(n){
            a[n%10]++;
            b[n%10]++;
            n/=10;
        }
        long long mx=0,mn=0;
        for(int i=9;i>=0;i--){
            while(a[i]-->0){
                mx*=10;
                mx+=i;
            }
        }
        int flag=0;
        for(int i=1;i<10;i++){
            while(b[i]-->0){
                mn*=10;
                mn+=i;
                if(!flag){
                    while(b[0]-->0)
                        mn*=10;
                    flag=1;
                }
            }
        }
        cout<<mx<<" - "<<mn<<" = "<<mx-mn<<" = 9 * "<<(mx-mn)/9<<endl;
    }
}

Comments