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 };
  • 相关阅读:
    Codeforces977D ---Divide by three, multiply by two 深搜+map存出现的数
    HDU4522 湫湫系列故事——过年回家
    2018浙江省赛记录
    POJ3259 :Wormholes(SPFA判负环)
    上海高校金马五校赛 F题:1 + 2 = 3?
    牛客练习赛15A-吉姆的运算式(Python正则表达式瞎搞)
    ZOJ2018/4月月赛G题Traffic Light(广搜)
    luogu 3960 列队
    noip2017
    10.3 模拟赛
  • 原文地址:https://www.cnblogs.com/easonliu/p/4355513.html
Copyright © 2011-2022 走看看