Permute Digits

You are given two positive integer numbers a and b. Permute (change order) of the digits of a to construct maximal number not exceeding b. No number in input and/or output can start with the digit 0.

It is allowed to leave a as it is.

Input

The first line contains integer a (1 ≤ a ≤ 1018). The second line contains integer b (1 ≤ b ≤ 1018). Numbers don't have leading zeroes. It is guaranteed that answer exists.

Output

Print the maximum possible number that is a permutation of digits of a and is not greater than b. The answer can't have any leading zeroes. It is guaranteed that the answer exists.

The number in the output should have exactly the same length as number a. It should be a permutation of digits of a.

Example
Input
123
222
Output
213
Input
3921
10000
Output
9321
Input
4940
5000
Output
4940

在调整过程中要判断大小,本来想是降序排序然后交换顺序,但是123和222,如果按照这样就是321,换3和2,就是231,还是大,然后就会换2和1,答案肯定不对,所以换了以后剩下的保持升序最好,也就是先升序排序,然后倒着把大的跟前面换,然后把剩下的升序排序,一直这么进行下去,纸上模拟了一遍可行。

代码:
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <cmath>
#include <algorithm>
using namespace std;
char s1[20],s2[20],s[20];
bool cmp(char a,char b)
{
    return a > b;
}
int main()
{
    int j;
    cin>>s1>>s2;
    if(strlen(s1) < strlen(s2))
    {
        sort(s1,s1 + strlen(s1),cmp);
    }
    else
    {
        sort(s1,s1 + strlen(s1));
        for(int i = 0;i < strlen(s1);i ++)
        {
            strcpy(s,s1);///保存原来的s1,如果交换不成功,还原,继续尝试其他交换
            for(j = strlen(s1) - 1;j > i;j --)
            {
                swap(s1[i],s1[j]);
                sort(s1 + i + 1,s1 + strlen(s1));
                if(strcmp(s1,s2) <= 0)break;
                else strcpy(s1,s);
            }
        }
    }
    cout<<s1;
}

 

转载于:https://www.cnblogs.com/8023spz/p/8361779.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值