LeetCode7 反轉整數
阿新 • • 發佈:2018-04-19
stand AR sign reverse char for with leetcode 開始
我的代碼:
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。
LeetCode7 反轉整數