2165. 重排数字的最小值

给你一个整数 num 。重排 num 中的各位数字,使其值 最小化 且不含 任何 前导零。

返回不含前导零且值最小的重排数字。

注意,重排各位数字后,num 的符号不会改变。

示例 1:

输入: num = 310
输出: 103
解释: 310 中各位数字的可行排列有:013、031、103、130、301、310 。
不含任何前导零且值最小的重排数字是 103 。

示例 2:

输入:num = -7605
输出:-7650
解释:-7605 中各位数字的部分可行排列为:-7650、-6705、-5076、-0567。
不含任何前导零且值最小的重排数字是 -7650 。

提示:

- 1 0 15 10^{15} 1015 <= num <= 1 0 15 10^{15} 1015

C++代码

#define pb push_back
typedef long long LL;
class Solution {
public:
    vector<int> nums;
    long long smallestNumber(long long num) {
        LL x = num > 0? num : -num;
        solve(x);
        LL ans = 0;
        if(num > 0){
            if(nums[0]){
                for(int i = 0; i < nums.size(); i ++)
                    ans = ans * 10 + nums[i];
            }else{
                int st = 0;
                while(! nums[st]) st ++;
                ans = nums[st];
                for(int i = 0; i < st; i ++) ans = ans * 10;
                for(int i = st + 1; i < nums.size(); i ++) ans = ans * 10 + nums[i];
            }
        }else if(num < 0){
            for(int i = nums.size() - 1; i >= 0; i --)
                ans = ans * 10 + nums[i];
            ans = -ans;
        }
        return ans;
    }
    
    void solve(LL x){
        while(x){
            nums.pb(x % 10);
            x /= 10;
        }
        sort(nums.begin(), nums.end());
        return ;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值