给定一个32位有符号整数,反转该数的数字

题目链接:https://leetcode.com/problems/reverse-integer/description/

例子:

Input: 123
Output:  321
Input: -123
Output: -321
Input: 120
Output: 21

 注意:超出范围时返回0

二、解答

思路:x%10可以得到最低位,x/10可以把最低位去除掉,然后以当前num乘10加上当前从x取出的最低位,最终得到结果。注意边界检查,反转是可能溢出的

 1 int reverse(int x) {
 2   long long num = 0;
 4   while (true) {
 5         if (x == 0)
 6             return num;
 7         if (num * 10 > INT_MAX || num * 10 < INT_MIN)
 8             return 0;
 9         num = num * 10 + x % 10;
10         x = x / 10;
11     }

 

相关文章:

  • 2022-01-08
  • 2021-10-03
  • 2021-06-19
  • 2021-10-31
  • 2021-08-07
  • 2021-11-09
  • 2021-06-07
猜你喜欢
  • 2021-04-05
  • 2021-10-27
  • 2021-11-01
  • 2021-12-01
  • 2022-01-03
  • 2021-12-16
  • 2021-08-05
相关资源
相似解决方案