# 【LeetCode】 7. Reverse Integer ## Description > Given a 32-bit signed integer, reverse digits of an integer. > 給一個32位元的有號數,請反轉該數字的每個位數。 ## Example: ``` Example 1: Input: 123 Output: 321 Example 2: Input: -123 Output: -321 Example 3: Input: 120 Output: 21 ``` ## Solution * 用`%10`把最低位元拿出來,用`*10`將每一位元推到下一位。 * 如果反轉後有溢位發生,直接輸出零。 ### Code ```C++=1 class Solution { public: int reverse(int x) { long long int ans=0; while(x!=0) { ans*=10; ans+=x%10; x/=10; } if((int)ans!=ans) ans=0; return (int)ans; } }; ``` ###### tags: `LeetCode` `C++`
×
Sign in
Email
Password
Forgot password
or
By clicking below, you agree to our
terms of service
.
Sign in via Facebook
Sign in via Twitter
Sign in via GitHub
Sign in via Dropbox
Sign in with Wallet
Wallet (
)
Connect another wallet
New to HackMD?
Sign up