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();
            
        }
    
    }
  • 相关阅读:
    Spring 学习十五 AOP
    Spring 学习十四 Spring security安全
    博客文格式优化
    作为一名软件测试工程师,需要具备哪些能力
    单元测试工程师需要具备的任职资格
    初识安全测试(一)
    压力测试工具JMeter入门教程
    Jmeter的优点是什么?除了轻量级,它和LoadRunner有什么本质区别
    初识Jmeter(一)
    初识Selenium(四)
  • 原文地址:https://www.cnblogs.com/zhoujunfu/p/4041846.html
Copyright © 2011-2022 走看看