思路
总的来说,就是转成字符串再拆分为多个数字字符 [ 0 , 1 , 2 , 3 , . . . . ] [0,1,2,3,....] [0,1,2,3,....]。
- 从小到大,排一下序为
nums
- 2个数字,一人依次到
nums
里面去拿一个数 - 最后2个数字相加就是结果了
代码
class Solution {
public:
int splitNum(int num) {
std::string num_string = std::to_string(num);
std::vector<int> nums;
for (int i = 0; i < num_string.length(); ++i)
{
nums.push_back(int(num_string[i]-'0'));
}
// for (auto item : nums) cout << item << " ";
sort(nums.begin(), nums.end(), less<int>());
// for (auto item : nums) cout << item << " ";
std::string firstNumStr;
std::string secondNumStr;
for (int i = 0; i < nums.size(); i+=2)
{
firstNumStr += (std::to_string(nums[i]));
if (i + 1 >= nums.size()) break;
secondNumStr += (std::to_string(nums[i + 1]));
}
int firstNum = std::stoi(firstNumStr);
int secondNum = std::stoi(secondNumStr);
return (firstNum + secondNum);
}
};