iT邦幫忙

0

刷 Leetcode 179 時碰到的問題,好像是不明原因出現garbage value

  • 分享至 

  • xImage

各位前輩好,本人在做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++高手提點,謝謝!

圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

1 個回答

3
meebox
iT邦新手 4 級 ‧ 2024-09-19 10:53:56
最佳解答

你的這一行:

return stoll(a + b) >= stoll(b + a);

是主要出錯的原因, 提供給 sortcmp 函數必須要符合 cmp(x, x) 一定是 false, 只要改成這樣就可以正確執行了:

return stoll(a + b) > stoll(b + a);
ffaanngg iT邦新手 5 級 ‧ 2024-09-19 12:29:29 檢舉

謝謝,原來還有這個小地方要注意,厲害

meebox iT邦新手 4 級 ‧ 2024-09-20 09:29:37 檢舉

可參考我整理的文章

我要發表回答

立即登入回答