C++ 反转整数:使用 exception 捕获溢出错误
class Solution {\npublic:\n int reverse(int x) {\n string s=to_string(x);//变成字符串\n std::reverse(s.begin(), s.end());//翻转字符串\n int ans=0;\n try{\n ans=stoi(s);//变回数字\n if (x<0) ans=-ans;//x是负数,加上负号\n }catch(exception ex){}//溢出,啥也不做,返回零\n return ans;\n }\n};这个exception ex是什么意思内容:"exception ex" is used to catch any exception that may occur during the execution of the code inside the try block. In this case, if an exception occurs when converting the reversed string back to an integer using stoi(), the catch block will be executed and the code inside it will be skipped.
原文地址: https://www.cveoy.top/t/topic/qiyD 著作权归作者所有。请勿转载和采集!