zoukankan      html  css  js  c++  java
  • Reverse Integer

    1     int reverse(int x) {
    2         int y=0;
    3         while(x)
    4         {
    5             y=y*10+x%10;
    6             x=x/10;
    7         }
    8         return y;
    9     }

    我试过了,不用区分是正数还是负数,他们的计算方法是一样的

    上面的代码虽然AC了,不过题上spoilers说的好,有可能会溢出,这个上述代码并没有考虑

    32位,1位符号位,剩下31位,表示范围 From −2,147,483,648 to 2,147,483,647, from −(231) to 231 − 1

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

     由于传进来的参数时int,参数本身不会溢出,但是逆转之后就可能会溢出了,关键是怎么判断逆转之后会溢出?

    我在codeblocks中试了一下,正数溢出之后会变成负数,负数溢出之后会变成正数

    下面的代码是写着玩的,因为函数返回值是int,所以即使用 long long 存储溢出的也不行的

     1     int reverse(int x) {
     2         int v=x;
     3         int y=0;
     4         while(x)
     5         {
     6             y=y*10+x%10;
     7             x=x/10;
     8         }
     9         //判断是否溢出
    10         //正数溢出为负数,负数溢出为正数
    11         if(v<=0&&y<=0||v>=0&&y>=0)//我觉得这么比x*y>0算的快一些
    12             return y;
    13         else
    14         {
    15             long long z=0;
    16             while(v)
    17             {
    18                 z=z*10+v%10;
    19                 v=v/10;
    20             }
    21             return z;   // 额,好吧,人家的函数返回值类型也是int型的
    22         }
    23     }

     在做String to Integer (atoi)这道题目时,我发现我判断溢出的方法是错的,并不能用输入正数返回负数或者输入负数返回正数来判断溢出的。怎么判断溢出呢?问问google吧

  • 相关阅读:
    【Gamma】Scrum Meeting 1
    【Gamma】设计与计划
    第五次作业 5.线性回归算法
    第四次作业 4.K均值算法--应用
    第三次作业 3.K均值算法
    第二次作业 2.机器学习相关数学基础
    第一次作业 机器学习概述
    第十五次 语法制导的语义翻译
    第十四次作业 算符优先分析
    第十三次作业 自下而上语法分析
  • 原文地址:https://www.cnblogs.com/crane-practice/p/3594102.html
Copyright © 2011-2022 走看看