• leetcode


    题目:Reverse Integer

    Reverse digits of an integer.

    Example1: x = 123, return 321
    Example2: x = -123, return -321

    click to show spoilers.

    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、将数字转换成字符串,如果是是负数,则将负号放在字符串末尾,然后字符串反转,再将字符串转换成数字即可
    2、上面的思路可以AC,但是没有考虑溢出的问题,由于这个问题并不在test case中,可以作为额外的思考题
    代码:
     1 #include <string>
     2 #include <iostream>
     3 
     4 using namespace std;
     5 
     6 class Solution
     7 {
     8 public:
     9     int reverse(int x)
    10     {
    11         char x_chars[64];
    12         int x_value = abs(x);
    13 
    14         if (x < 0)
    15         {
    16             sprintf(x_chars, "%d-", x_value);
    17         }
    18         else
    19         {
    20             sprintf(x_chars, "%d", x_value);
    21         }
    22         string x_string(x_chars);
    23         string x_reverse(x_string.rbegin(), x_string.rend());
    24 
    25         return atoi(x_reverse.c_str());
    26     }
    27 };
    28 
    29 int main()
    30 {
    31     Solution s;
    32     int test = s.reverse(-123490);
    33 
    34     cout << test << endl;
    35 
    36     system("pause");
    37 
    38     return 0;
    39 }
    View Code

    上网看了几篇文章,都是通过除以10和模10的方法来取得尾数,有一遍文章有对溢出问题的思考,链接:http://blog.csdn.net/littlestream9527/article/details/17059939

  • 相关阅读:
    zabbix监控部署(三)
    zabbix监控部署(二)
    zabbix监控部署(一)
    Docker安装mysql5.7
    Docker修改容器默认存储路径
    MySQL全量+增量备份脚本
    企业级Dokcer镜像仓库Harbor部署
    Linux环境pyhon3安装pyinstaller
    配置Hive元数据数据库为PostgreSQL
    Oracle 11gR2 RAC 添加节点
  • 原文地址:https://www.cnblogs.com/laihaiteng/p/3804886.html
Copyright © 2020-2023  润新知