zoukankan      html  css  js  c++  java
  • 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).

    Solution: Use % and / iteratively.

     1 class Solution {
     2 public:
     3     int reverse(int x) {
     4         long long res = 0;
     5         while (x) {
     6             res = res * 10 + (x % 10);
     7             x /= 10;
     8         }
     9         assert(res <= INT_MAX && res >= INT_MIN);
    10         return res;
    11     }
    12 };
  • 相关阅读:
    轻时代来临 资深架构师分享手游五大设计要点
    Netty 介绍
    Socket编程与线程
    java多线程并发访问解决方案
    throws 和throw 的区别
    JRE
    Servlet的生命周期
    页面介绍
    项目技术介绍
    软件开发环境
  • 原文地址:https://www.cnblogs.com/zhengjiankang/p/3631694.html
Copyright © 2011-2022 走看看