zoukankan      html  css  js  c++  java
  • [Leetcode] Reverse Integer

    Reverse digits of an integer.

    Example1: x = 123, return 321
    Example2: x = -123, return -321

    click to show spoilers.

    Have you thought about this?

    Here are some good questions to ask before coding. Bonus points for you if you have already thought through this!

    If the integer's last digit is 0, what should the output be? ie, cases such as 10, 100.

    Did you notice that the reversed integer might overflow? Assume the input is a 32-bit integer, then the reverse of 1000000003 overflows. How should you handle such cases?

    For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.

    Update (2014-11-10):
    Test cases had been added to test the overflow behavior.

    给定的数字经过逆序有可能会整形越界,最简单的方法就是把结果用精度更高的类型来存,最后判断有没有越界。
     1 class Solution {
     2 public:
     3     int reverse(int x) {
     4         long long res = 0, tmp = x;
     5         bool sign = true;
     6         if (x < 0) {
     7             sign = false;
     8             tmp = -tmp;
     9         }
    10         int digit;
    11         while (tmp != 0) {
    12             digit = tmp % 10;
    13             res *= 10;
    14             res += digit;
    15             tmp /= 10;
    16         }
    17         res = sign ? res : -res;
    18         return (res < INT_MIN || res > INT_MAX) ? 0 : res;
    19     }
    20 };

    如果不用更高精度来存的话,就得在运算过程中来判断有没有越界了。方法就是在乘10前先比较一下当前值与INT_MAX/10的大小,若比后者大,说明乘10后就越界了。

     1 class Solution {
     2 public:
     3     int reverse(int x) {
     4         int res = 0, tmp = x;
     5         bool sign = true;
     6         if (x < 0) {
     7             sign = false;
     8             if (tmp == INT_MIN) return 0;
     9             tmp = -tmp;
    10         }
    11         int digit;
    12         while (tmp != 0) {
    13             digit = tmp % 10;
    14             if (INT_MAX / 10 < res) return 0;
    15             res *= 10;
    16             res += digit;
    17             tmp /= 10;
    18         }
    19         return sign ? res : -res;
    20     }
    21 };
  • 相关阅读:
    informatica 学习日记整理
    informatica 学习日记整理
    执行异步任务,并记录时间
    Calling a Web API From a .NET Client (C#)
    PIVOT运算符使用(动态行转列)
    Replication--如何使用快照来初始化化请求订阅
    Replication--备份初始化需要还原备份么?
    疑难杂症--SQL SERVER 18056的错误
    TSQL--如何突破PRINT的8000大限
    执行计划--在存储过程中使用SET对执行计划的影响
  • 原文地址:https://www.cnblogs.com/easonliu/p/4355513.html
Copyright © 2011-2022 走看看