tungggg

Leetcode reverse integer

Mar 20th, 2022
52
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.53 KB | None | 0 0
  1. #include<bits/stdc++.h>
  2. using namespace std;
  3. class Solution {
  4. public:
  5.     int reverse(int x) {
  6.         string s = to_string (x);
  7.         if ( s[0] =='-') s.erase(s.begin());
  8.         std::reverse(s.begin(),s.end());
  9.         for (int i=0;i<s.size();i++){
  10.             if ( s[i]!='0'){
  11.                 s=s.substr(i);
  12.                 break;
  13.             }
  14.         }
  15.        
  16.         long long real = stoll ( s);
  17.         if ( real > 2147483648 ) return 0; // 2^31-1 = 2147483648
  18.         return x>0? stoi(s) : -stoi(s);
  19.     }
  20. };
Advertisement
Add Comment
Please, Sign In to add comment