各位前輩好,本人在做leetcode 179時碰到以下問題:
先放上可以被accept的解答:
class Solution {
public:
static bool comp(const int& A, const int& B) {
string a = to_string(A), b = to_string(B);
return a+b > b+a;
}
string largestNumber(vector<int>& nums) {
sort(nums.begin(), nums.end(), comp);
string res = "";
if (nums[0] == 0) return "0";
for (int num:nums) {
res += to_string(num);
}
return res;
}
};
但我如果用在comp裡用stoll()的話就會出現奇怪的問題 (加上cout來debug):
class Solution {
public:
static bool comp(const int& A, const int& B) {
cout << "A: " << A << " B: " << B << endl; // Print the actual values
string a = to_string(A), b = to_string(B);
cout << "Concatenated: " << a + b << " vs " << b + a << endl;
return stoll(a + b) >= stoll(b + a);
}
string largestNumber(vector<int>& nums) {
sort(nums.begin(), nums.end(), comp);
string res = "";
if (nums[0] == 0) return "0";
for (int num:nums) {
res += to_string(num);
}
return res;
}
};
跑這個testcase:
nums = [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]
會跳出 heap-buffer-overflow 的錯誤,且印出
(省略前面)
A: 0 B: 0
Concatenated: 00 vs 00
A: -1094795586 B: 0
Concatenated: -10947955860 vs 0-1094795586
A: 0 B: 0
Concatenated: 00 vs 00
(省略後面)
這個 -1094795586 明顯是 garbage value,不知從何而來,麻煩c++高手提點,謝謝!