zoukankan      html  css  js  c++  java
  • Java [leetcode 7] 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?

    For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.

    解题思路:

    需要考虑数值为负的情况,需要考虑数值反过来后溢出的情况。

    代码如下:

    public class Solution {
        public int reverse(int x) {
    		final String LowerValue = "2147483648";
    		final String UpperValue = "2147483647";
    		final int maxlength = 10;
    		String sOriginal = String.valueOf(x);
    		String sReverse = stringReverse(sOriginal);
    		String sfinal = new String();
    		int reversenum;
    		
    		if (sReverse.charAt(sReverse.length() - 1) == '-') {
    			sfinal = sReverse.substring(0, sReverse.length() - 1);
    			if (sfinal.length() >= maxlength && sfinal.compareTo(LowerValue) > 0)
    				reversenum = 0;
    			else
    				reversenum = -Integer.valueOf(sfinal).intValue();
    		} else {
    			sfinal = sReverse;
    			if (sfinal.length() >= maxlength && sfinal.compareTo(UpperValue) > 0)
    				reversenum = 0;
    			else
    				reversenum = Integer.valueOf(sfinal).intValue();
    		}
    		return reversenum;
    	}
    
    	public String stringReverse(String s) {
    		StringBuilder stringBuilder = new StringBuilder(s);
    		stringBuilder.reverse();
    		return stringBuilder.toString();
    	}
    }
    
  • 相关阅读:
    .NetCore教程之 EFCore连接Mysql DBFirst模式
    .Net EF6+Mysql 环境搭建
    SQL实用
    前端文章分享
    mac怎样运行vue项目
    Cadence 操作技巧总结3:拼板技巧总结
    TCL语言控制Modelsim仿真 2
    TCL语言控制Modelsim仿真 1
    Cadence 操作技巧总结2:模块化布局
    Cadence 操作技巧总结1:测试点的生成1
  • 原文地址:https://www.cnblogs.com/zihaowang/p/4455831.html
Copyright © 2011-2022 走看看