我的代码:
class Solution { public: int reverse(int x) { int sign=x<0?1:0; string maxint="2147483647"; string minint="2147483648"; //int to string string snum=""; int tem=x; char ctem; while(tem!=0){ //standard has itoa ctem=abs(tem%10)+'0'; snum=ctem+snum; tem/=10; } std::reverse(snum.begin(),snum.end()); if(snum.size()==10){ if(sign==0){ if(snum>maxint){ return 0; } } else{ if(snum>minint){ return 0; } if(snum==minint){ return -2147483648; } } } int result=0; for(int i=0;i<snum.size();i++){ result=(snum[i]-'0')+result*10; } if(sign==0){ return result; } else{ return -result; } } };
一开始24ms,加了关闭同步后12ms。超越96%的代码。
别人的代码:
static int x = []() { std::ios::sync_with_stdio(false); cin.tie(NULL); return 0; }(); class Solution { public: int reverse(int x) { int flag = 1; if (x < 0) { x = -x; flag = -1; } int64_t sum = 0; while (x > 0) { sum = sum * 10 + x % 10; x /= 10; } sum = sum * flag; return (sum > INT32_MAX || sum < INT32_MIN) ? 0 : sum; } };
5ms。