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最好不过。

  • 相关阅读:
    Axis2发布Webservice进行身份校验
    Spring集成Axis2
    分布式事务解决方案之TCC
    Lua 数据类型
    Lua 基本语法(1)
    Axis发布Webservice服务
    Linux中NFS服务器搭建
    SpringBoot多环境切换
    springboot中spring.profiles.include的妙用
    oracle树形语句
  • 原文地址:https://www.cnblogs.com/changchengxiao/p/3415319.html
Copyright © 2011-2022 走看看