C++ || Easy-Understanding || strings || Beats 100%
  • first covert the number to string
  • then reverse the string
  • compute the numerical value of the reversed number from the string (using long to avoid overflow)
  • if the computed number goes out of range return 0 else return the computed number
class Solution {
public:
    int reverse(int x) {
        bool isNegative = x < 0 ;
        string str = to_string(abs(x)) ; 
        str = string(str.rbegin() , str.rend()) ; // reverse the string to get string equivalent of reversed number
        long ans = 0 ;
        for(char x : str) ans = 10 * ans + (x - '0') ; // calculate numeric value from reversed string
        if(ans < -1 * pow(2 , 31) || ans > pow(2 , 31) - 1) return 0 ; // out of range
        return isNegative ? -1 * ans : ans ;
    }
};
Comments (0)