zoukankan      html  css  js  c++  java
  • Reverse Integer [LeetCode]

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

    Solution: be careful about corner case, like INT_MIN, 0, and -INT_MIN is not equals to INT_MAX.  Here is the definition of them in limits.h

    #define INT_MIN     (-2147483647 - 1) /* minimum (signed) int value */
    #define INT_MAX       2147483647    /* maximum (signed) int value */
     1     int reversePostiveInt(int x){
     2         vector<int> digits;
     3         while(true) {
     4             if(x < 10 ){
     5                 digits.push_back(x);
     6                 break;
     7             }else {
     8                 int remainder = x % 10;
     9                 int quotient = x / 10;
    10                 digits.push_back(remainder);
    11                 x = quotient;
    12             }
    13         }
    14         // reverse output
    15         long long int ret = 0;
    16         for(int i = 0; i < digits.size(); i ++) {
    17             ret = ret * 10 + digits[i];
    18             if(ret > INT_MAX){
    19                 ret = INT_MAX;
    20                 break;
    21             }
    22         }
    23         return (int) ret;
    24     }
    25     
    26     int reverse(int x) {
    27         if(x == 0 )
    28             return 0;
    29         if(x > 0) {
    30            return reversePostiveInt(x);
    31         }else if( x == INT_MIN){
    32             //overflow
    33             return INT_MIN;
    34         }else if ( x > INT_MIN) {
    35             return -reversePostiveInt(-x);
    36         }
    37     }
  • 相关阅读:
    python--tkinter桌面编程开发--记事本
    Python--面向对象编程
    Python--面向对象编程--时钟实例开发
    Python学习笔记--2--面向对象编程
    Python学习笔记--1
    epoll聊天室的实现
    操作系统--虚拟存储器
    操作系统--存储器管理
    操作系统--分页存储管理中逻辑地址转换为物理地址
    操作系统--处理机调度与死锁
  • 原文地址:https://www.cnblogs.com/guyufei/p/3404611.html
Copyright © 2011-2022 走看看