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();
            
        }
    
    }
  • 相关阅读:
    基于ESFramework的P2P实现 —— ESFramework扩展之EsfP2P
    反射中使用 BindingFlags.IgnoreCase
    DTS开发记录(8)-- 主键的影响
    双向链表
    const_iterator和const iterator的区别
    顺序队列
    谈一谈网络编程学习经验
    使用模板元编程快速的得到斐波那契数。。
    数组的选择固定大小数组模板array存在的意义!
    C++查缺补漏2,赶紧的
  • 原文地址:https://www.cnblogs.com/zhoujunfu/p/4041846.html
Copyright © 2011-2022 走看看