zoukankan      html  css  js  c++  java
  • LeetCode--Reverse Integer

    Reverse digits of an integer.

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

    思路:

      很简单的思路,对x对10取余数,把x从低位到高位的数字依次提取出来,再每次对结果乘10加上新取出的个位,最后x=x/10,循环到x为0为止。

    public class Solution {
        public int reverse(int x) {
            int result = 0;
            while(x!=0){
                result = result*10+x%10;
                x /=10;
            }
            return result;
            
        }
    }

     Spoiler:

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

      spoiler指出了要考虑溢出的情况,32位有符号整数的取值范围是-2147483648~2147483647,一共2^32次方个,从新写了个带判断溢出的结果,判断依据是正数加正数如果为负数了则是溢出,负数加负数为正数了也是溢出。

    package com.bupt.tools;
    import java.util.Scanner;
    public class Test {
        
        private static boolean flag;
        
        public static int reverseint(int x){
            flag = false;
            int sign=x>0?1:-1;
            int result = 0;
            while(x!=0){
                result = result*10+x%10;
                x/=10;
            }
            if(sign==1){
                if(result<0){
                    flag = true;
                    return -1;
                }
            }
            else if(sign==-1){
                if(result>0){
                    flag = true;
                    return -1;
                }        
            }
            return result;
        }
        
        public static void main(String[] args){
            Scanner sc = new Scanner(System.in);
            
            while(sc.hasNext()){
                int result = Test.reverseint(sc.nextInt());
                if(!Test.flag)
                    System.out.println(result);
                else
                    System.out.println("Overflow!");
             }
            sc.close();
            
        }
    
    }
  • 相关阅读:
    CodeForces 604D 【离散数学 置换群】
    CodeForces 604C 【思维水题】`
    CodeForces 602E【概率DP】【树状数组优化】
    CodeForces 602D 【单调队列】【简单数学】
    HDU 3535 【背包】
    CodeForces 593D【树链剖分】
    HYSBZ 1036 【树链剖分】
    POJ 2352 【树状数组】
    POJ 2182【树状数组】
    机器学习实战笔记-2-7分类机器学习形象化总结
  • 原文地址:https://www.cnblogs.com/zhoujunfu/p/4041846.html
Copyright © 2011-2022 走看看