LeetCode2 Reverse Interger


summary:
1. to_string(int x): int to string, should include <string>;
2. pow(x,y): calculate x<sup>y</sup>;
3. the min number of 32 bit integer is -2147483648, but cannot use the number to compare or assignment.Question:
Given a 32-bit signed integer, reverse digits of an integer.

question:

Example 1:

Input: 123
Output: 321
Example 2:

Input: -123
Output: -321
Example 3:

Input: 120
Output: 21
Note:
Assume we are dealing with an environment which could only store integers within the 32-bit signed integer range: [−231,  231 − 1]. For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.
 

answer:

class Solution {
public:
    int reverse(int x) {
        int temp = x;
        if (x < 0) {
            temp = -x;
        }
        string str = to_string(temp);
        int result = 0;
        for (int i = 0; i < str.length(); ++i) {
            result += (str[i]-'0') * pow(10, i);
        }
        if (x < 0) result = -result;

        if (result < -2147483647) return 0;
        else return result;
    }
};

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章