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

  • 相关阅读:
    Google 面试准备清单
    Two sorted array. Find kth smallest element, 要求O(logK)
    MVC(demo)
    UE4学习心得:Scene Component蓝图的一个简单应用
    UE4中如何使物体始终朝向摄像头?
    响应式Web设计
    Nodejs的express使用教程
    安装express遇到的问题
    致自己
    上传文件的方法
  • 原文地址:https://www.cnblogs.com/changchengxiao/p/3415319.html
Copyright © 2011-2022 走看看