【C++】LeetCode 力扣周赛279 第二题 题解
题目链接
2165. 重排数字的最小值 - 力扣(LeetCode) (leetcode-cn.com)
题目要求
给你一个整数num
。重排num
中的各位数字,使其值最小化且不含任何前导零。
返回不含前导零且值最小的重排数字。
注意,重排各位数字后num
的符号不会改变。
思路
首先将num
中的每位数字分别放入整型数组res
中,对res
使用sort排序
对num
的正负性进行考虑,如果num
为正数,那么反转res
数组方便后续计算,如果num
为正数且含零,那么res[0]
一定为0,将res[0]
与第一位非零数字res[k]
交换。
然后依位次加和得到结果sum
,若原num
为负数,则对sum
取相反数。
输出结果sum
注意题中要求为long long 类型
详细代码
class Solution
{
public:
long long smallestNumber(long long num)
{
if (num == 0)
return 0;
vector<int> res;
long long temp = abs(num);
long long i = 1;
while (i <= temp)
{
long long t = temp / i;
res.push_back(t % 10);
i = i * 10;
}
sort(res.begin(), res.end());
long long sum = 0;
int n = res.size();
if (num > 0)
{
int k = 0;
while (res[k] == 0)
k++;
swap(res[k], res[0]);
reverse(res.begin(), res.end());
}
for (int j = 0; j < n; j++)
{
sum += res[j] * pow(10, j);
}
if (num < 0)
sum = -sum;
return sum;
}
};