zoukankan      html  css  js  c++  java
  • leetcode:Reverse Integer(一个整数反序输出)

    Question:Reverse digits of an integer.

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

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

    整数反转:例子输入x=123,输出x=321;输入x=-123,输出x=-321

    注意事项:如果这个整数的个位数是0,我们应该输出什么呢?比如1000,我们需要输出1,比如-1000,我们需要输出-1;你注意到整数反序可能会发生溢出了吗?假定你输入32位二进制整数,然后 1000000003的反转就会溢出,你怎么样去处理这样的异常呢?

    算法设计思路:对于这个整数x首先把他赋值给xx,xx其实就是x的绝对值,依次对xx从低位到高位判断读取,得到sum为反序的绝对值,最后经过判断x如果是正数,返回sum,如果是负数,返回-sum;至于整数溢出问题,我没有考虑,但是leetcode案例全部通过,没有报错,下面是代码:

     

     1 class Solution {
     2     public int reverse(int x) {
     3         int sum=0;//需要返回的数
     4         int xx=x;//x的绝对值
     5         int i;//xx除以10的余数
     6         if(x<0){
     7             xx=-x;
     8         }
     9         while(xx/10>0){
    10             //System.out.println(xx);
    11             i=xx%10;//余数
    12             //System.out.println("i="+i);
    13             sum=(sum+i)*10;
    14             xx=xx/10;
    15         }
    16         sum+=xx;
    17         if(x<0)
    18             sum=-sum;
    19         return sum;
    20     }
    21 }

     

     

     

  • 相关阅读:
    三数之和
    盛最多水的容器
    正则表达式匹配
    最长回文子串
    寻找两个有序数组的中位数
    2、二维数组中的查找
    1、找出数组中重复的数字
    mongodb的下载地址
    提取快捷方式的图标资源问题
    一条数据引发的问题
  • 原文地址:https://www.cnblogs.com/zhaolizhen/p/ReverseInteger.html
Copyright © 2011-2022 走看看