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大/小就行

  • 相关阅读:
    java----session
    js封装成插件-------Canvas统计图插件编写
    js封装成插件
    js学习--变量作用域和作用域链
    学习js函数--自执行函数
    学习js函数--函数定义
    footer不满一屏时在最底部,超出一屏时在页面最下部
    ios 点击区域阴影问题
    提交表单后数据返回时间过长
    点击显示video
  • 原文地址:https://www.cnblogs.com/lailailai/p/3806044.html
Copyright © 2011-2022 走看看