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

     1 class Solution {
     2 public:
     3     int reverse(int x) {
     4         
     5         int flag = 0;
     6         if(x < 0)
     7         {
     8             flag = -1;
     9             x = -x;
    10         }
    11         
    12         int result = 0;
    13         int k = 1;
    14         vector<int> figure;
    15         
    16         while(x / 10 != 0)
    17         {
    18             figure.push_back(x % 10);
    19             x /= 10;
    20         }
    21         figure.push_back(x);
    22         
    23         for(int i = figure.size()-1; i >= 0; i--, k *= 10)
    24         {
    25             result += figure[i] * k;
    26         }
    27         
    28         if(flag == -1)
    29             result = -result;
    30             
    31         return result;
    32     }
    33 
    34 };
  • 相关阅读:
    单例模式
    堆排序--leetcode 215
    二叉树--路径问题
    二叉树--前中后序两两结合构建二叉树
    CglibProxy
    JdkProxy
    git config --global http.sslVerify false
    PdfUtil
    idea中创建的文件类型无法识别
    sql优化
  • 原文地址:https://www.cnblogs.com/YQCblog/p/3970174.html
Copyright © 2011-2022 走看看