zoukankan      html  css  js  c++  java
  • LeetCode Reverse Integer

    class Solution {
    public:
        int reverse(int x) {
            bool neg = x < 0;
            long long num = x;
            if (neg) num = -num;
            long long out = 0;
            while (num) {
                out = out * 10 + num % 10;
                num /= 10;
            }
            if (neg) return -out;
            return out;
        }
    };

    再水

    第二轮:

    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.

    用int来做:

     1 class Solution {
     2 public:
     3     int reverse(int x) {
     4         int val = 0;
     5         int pos_threshold = INT_MAX/10;
     6         int neg_threshold = INT_MIN/10;
     7         bool positive = x >= 0;
     8         while (x) {
     9             int d = x % 10;
    10             if (positive) {
    11                 if (val > pos_threshold) {
    12                     val = 0;
    13                     break;
    14                 }
    15             } else {
    16                 if (val < neg_threshold) {
    17                     val = 0;
    18                     break;
    19                 }
    20             }
    21             val = val * 10 + d;
    22             
    23             x = x / 10;
    24         }
    25         return val;
    26     }
    27 };

    因为是数字逆转,原来的输入数据也是在int范围内,所以如果数字长度是10位则第一位也只能是1或者2,所以只需判断前一次的结果值是否比threshold大/小就行

  • 相关阅读:
    Python:Fatal error in launcher: Unable to create process using 问题排查
    接口测试及接口Jmeter工具介绍
    bug的分类和等级
    如何编写测试用例
    网络流入门--最大流算法Dicnic 算法
    Codevs 1004 四子连棋
    洛谷 P1072 Hankson 的趣味题
    Codevs 搜索刷题 集合篇
    洛谷 P1195 口袋的天空
    洛谷 P1362 兔子数
  • 原文地址:https://www.cnblogs.com/lailailai/p/3806044.html
Copyright © 2011-2022 走看看