zoukankan      html  css  js  c++  java
  • leetcode 7. Reverse 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?

    For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.

    Update (2014-11-10):
    Test cases had been added to test the overflow behavior. 
     
    这道题实现并不难,就是溢出问题。
    32位有符号数,最高位表示符号,剩下31位表示数值,那么最大可以表示0x7fffffff,最小可以表示0x80000000
    我们要处理溢出的情况,在reverse的过程中,有可能会出现溢出的情况,此时要返回0
     
     1 class Solution {
     2 public:
     3     int reverse(int x) {
     4         
     5         const int max = 0x7fffffff;  //int最大值
     6         const int min = 0x80000000;  //int最小值
     7         long long sum = 0; 
     8         
     9         while(x != 0)
    10         {
    11             int temp = x % 10;
    12             sum = sum * 10 + temp;
    13             if (sum > max || sum < min)  return 0;   //处理溢出
    14             x = x / 10;
    15         }
    16         return sum;
    17     }
    18 };
  • 相关阅读:
    移位运算符的限制
    数据类型
    正无穷和负无穷的问题
    dos下的cd指令
    c#线程的几种启动方法
    储过程实现简单的数据分页
    java 身份证15位转18位
    eclipse配置文件内存设置
    markdown语法学习
    js工具类
  • 原文地址:https://www.cnblogs.com/LUO77/p/5073435.html
Copyright © 2011-2022 走看看