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).

     1 class Solution {
     2 public:
     3     int reverse(int x) {
     4         int ret = 0;
     5         bool sign = true;
     6         if (x < 0) {
     7             x = -x;
     8             sign = false;
     9         }
    10         while (x) {
    11             ret = ret * 10 + x % 10;
    12             x /= 10;
    13         }
    14         return sign ? ret : -ret;
    15     }
    16 };
  • 相关阅读:
    RF04 Variables
    RF06 Settings
    RF05 Keywords
    Nginx介绍
    javascript中的迷惑点
    javascript中的undefined和null
    常见博客网站的robots.txt
    CSS层叠样式表
    web前端校验
    了解javascript
  • 原文地址:https://www.cnblogs.com/dengeven/p/4009307.html
Copyright © 2011-2022 走看看