题目链接:https://leetcode.com/problems/reverse-integer/description/
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: [?2^31, 2^31 ? 1]. For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.
思路:
- 对待处理的整数X,拷贝一份并命名为 copy,取拷贝值的绝对值进行下述数据处理;
- 用长整型变量 ans 来存储翻转后的数值, ans变量赋初值为0; 当copy > 0 时对copy进行整除和取余操作:
-
- int cur = copy % 10; // 当前处理的数位的值
- ans = ans * 10 + cur;
- copy = copy / 10;
- 对求得的ans值进行范围检验;
- 若X值为正数,则返回ans;若X值为负数,则返回 -ans 。
编码如下:
1 class Solution { 2 public: 3 int reverse(int x) { 4 // 若数值不在 [?2^31, 2^31 ? 1]范围内,则返回0 5 //if (x < (1 << 31) || x > (~(1 << 31))) return 0; 6 7 // 若x属于[-9, 9]这个范围内,则返回x 8 if (-10 < x && x < 10) return x; 9 10 // 其他情况 11 long int ans = 0; 12 int copy = (x >= 0 ? x : -x); 13 14 while (copy > 0) 15 { 16 int cur = copy % 10; // 当前处理的数位值 17 ans = ans * 10 + cur; 18 copy = copy / 10; 19 } 20 21 ans = (x >= 0 ? ans : -ans); 22 if (ans < (1 << 31) || ans > (~(1 << 31))) return 0; 23 24 return static_cast<int>(ans); 25 } 26 };
原文地址:https://www.cnblogs.com/ming-1012/p/9907702.html
时间: 2024-11-10 00:08:54