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

    Reverse digits of an integer.

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

    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?

    Throw an exception? Good, but what if throwing an exception is not an option? You would then have to re-design the function (ie, add an extra parameter).

    先给出代码。

    class Solution {
    public:
        int reverse(int x) {
            // IMPORTANT: Please reset any member data you declared, as
            // the same Solution instance will be reused for each test case.
            int ans = 0;
            while(x)
            {
                ans = ans * 10 + x % 10;
                x = x / 10;
            }
            return ans;
        }
    };

    下面回答几个疑问:

    1. 如果末尾有零,输出应该是什么?

    当前的算法因为是累加生成最终的integer,故首位不可能为零。如果用string做交换操作则需要考虑去掉前导零。

    2. 如果有溢出,如何处理?

    由于给定函数的返回值是int,故如果出现溢出,无法范围实际的结果。此时可以考虑负数取最小int,正数取最大int返回。当然如果能返回string最好不过。

  • 相关阅读:
    域控软件分发
    win2008 ad域控搭建
    tomcat部署web项目的三种方式
    sql server2008数据库迁移的两种方案
    WinServer2008R2远程桌面长时间保持连接
    Windows2012R2备用域控搭建
    主备 主从 主主模式
    excel中汉字转拼音
    正向代理与反向代理
    18-09-11 软件rpm yum rm卸载 和批量删除
  • 原文地址:https://www.cnblogs.com/changchengxiao/p/3415319.html
Copyright © 2011-2022 走看看