LeetCode - 7. Reverse Integer【逆序輸出整數】
阿新 • • 發佈:2018-12-16
題目
Given a 32-bit signed integer, reverse digits of an integer.
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
題意
輸入一個32位整數,要求逆序輸出。
分析
樣例1、2正常逆序輸出;
樣例3輸入數字末尾帶0,逆序輸出時應當捨去0。
*if(!x) 表示條件為0執行語句,while(x)表示持續執行直到x=0。
*先將int型轉換成longlong型,最後判斷是否溢位。
程式碼
class Solution { public: int reverse(int x) { if(!x) return 0; while(x % 10 == 0) x /= 10; long long sum = 0; while(x) { sum = sum * 10 + x % 10; x /= 10; } int numb = sum; if(numb == sum) return numb; else return 0; } };
待解
class Solution {public:}含義?