zoukankan      html  css  js  c++  java
  • [leetcode] Reverse Integer

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

    https://oj.leetcode.com/problems/reverse-integer/

    思路:从低到高依次取得数字的每一位累加到新数字中。

    public class Solution {
    	public int reverse(int x) {
    		int result = 0;
    		boolean neg = false;
    		if (x < 0) {
    			neg = true;
    			x = -x;
    		}
    		int a = 0;
    		while (x != 0) {
    			a = x % 10;
    			x /= 10;
    			result = result * 10 + a;
    		}
    		if (neg)
    			result = -result;
    		return result;
    
    	}
    
    	public static void main(String[] args) {
    		System.out.println(new Solution().reverse(123));
    		System.out.println(new Solution().reverse(-123));
    		System.out.println(new Solution().reverse(1));
    		System.out.println(new Solution().reverse(-1));
    		System.out.println(new Solution().reverse(0));
    	}
    }

     第二遍记录:

      注意负数的情况

      溢出的话  用long保存中间结果,然后判断Integer.MAX_VALUE比较。

    public class Solution {
        public int reverse(int x) {
            int res=0;
            boolean neg =false;
            if(x<0){
                neg=true;
                x=-x;
            }
            int digit=0;
            while(x!=0){
                digit= x%10;
                x = x/10;
                res =res*10+digit;
            }
            
            return neg?-res:res;
            
        }
    }

    参考:

    http://www.cnblogs.com/TenosDoIt/p/3735866.html

  • 相关阅读:
    Educational Codeforces Round 1 (C) (atan2 + long double | 大数)
    AC自动机模板
    JSP 过滤器
    JSP 动作元素
    Hibernate 拦截器
    Hibernate 批处理
    Hibernate 缓存
    单例模式数据库连接
    JavaScript限制前端页面用户表单输入
    注册页面手机验证码无跳转接收[html+js+ajax+php]
  • 原文地址:https://www.cnblogs.com/jdflyfly/p/3810676.html
Copyright © 2011-2022 走看看