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

  • 相关阅读:
    C++虚继承内存布局
    编译OpenJDK记录
    Node.js + Express 调研
    软件工程开发工具
    Servlets & JSP & JavaBean 参考资料
    Eclipse AST 相关资料
    Git & github 最常用操作笔记
    Java入门学习资料整理
    从变量的类型转换看C语言的思维模式
    数学地图(1)
  • 原文地址:https://www.cnblogs.com/lailailai/p/3806044.html
Copyright © 2011-2022 走看看