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 };
  • 相关阅读:
    linux gcc安装
    重装win7后如何恢复ubuntu引导
    Eclipse搭建Android开发环境(安装ADT,Android4.4.2)
    mysql变量使用总结
    最快得到MYSQL两个表的差集
    mysqldb
    更改时间 (时分秒)
    使用命令转移文件
    报喜啦~过了!
    Jmeter接口测试示例
  • 原文地址:https://www.cnblogs.com/YQCblog/p/3970174.html
Copyright © 2011-2022 走看看