1. 程式人生 > >【LeetCode】124.Reverse Integer

【LeetCode】124.Reverse Integer

題目描述(Easy)

Given a 32-bit signed integer, reverse digits of an integer.

題目連結

https://leetcode.com/problems/reverse-integer/description/

Example 1:

Input: 123
Output: 321

Example 2:

Input: -123
Output: -321

Example 3:

Input: 120
Output: 21

演算法分析

無,注意數值溢位。

提交程式碼:

class Solution {
public:
	int reverse(int x) {
		if (x == INT_MIN) return 0;
		int res = 0;
		int y = x > 0 ? x : -x;
		bool sign = x > 0 ? true : false;

		for (; y; y /= 10)
		{
			if ((INT_MAX - y % 10) / 10 < res)
				return 0;
			res = 10 * res + y % 10;
		}

		return sign ? res : -res;
	}
};