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 };
  • 相关阅读:
    行内块 块级元素 行内元素
    3种飞翼布局
    emmit
    Linux基础命令
    关于微信小程序下拉出现三个小点
    关于vue,angularjs1,react之间的对比
    微信小程序开发遇见的问题之一
    关于微信小程序的尺寸关系
    关于微信小程序的开发步骤
    关于前端基础知识的一些总结
  • 原文地址:https://www.cnblogs.com/LUO77/p/5073435.html
Copyright © 2011-2022 走看看