Fork me on GitHub

reverse-integer

/**
*
* @author gentleKay
* Reverse digits of an integer.
* Example1: x = 123, return 321
* Example2: x = -123, return -321
* click to show spoilers.
* 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).
*
* 整数的倒数。
* 示例1:x=123,返回321
* 示例2:x=-123,返回-321
* 单击以显示扰流器。
* 你想过这个吗?
* 在编码之前,这里有一些好问题要问。如果你已经考虑过了,就可以给你加分!
* 如果整数的最后一位是0,那么输出应该是什么?例如,10,100个案例。
* 您注意到反转的整数可能溢出吗?假设输入是32位整数,则10000000003的反向溢出。
* 你该如何处理这些案件?
* 是否引发异常?很好,但是如果抛出异常不是一种选择呢?
* 然后您必须重新设计函数(即,添加一个额外的参数)。
*/

/**
 * 
 * @author gentleKay
 * Reverse digits of an integer.
 * Example1: x = 123, return 321
 * Example2: x = -123, return -321
 * click to show spoilers.
 * 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).
 * 
 * 整数的倒数。
 * 示例1:x=123,返回321
 * 示例2:x=-123,返回-321
 * 单击以显示扰流器。
 * 你想过这个吗?
 * 在编码之前,这里有一些好问题要问。如果你已经考虑过了,就可以给你加分!
 * 如果整数的最后一位是0,那么输出应该是什么?例如,10,100个案例。
 * 您注意到反转的整数可能溢出吗?假设输入是32位整数,则10000000003的反向溢出。
 * 你该如何处理这些案件?
 * 是否引发异常?很好,但是如果抛出异常不是一种选择呢?
 * 然后您必须重新设计函数(即,添加一个额外的参数)。
 */

public class Main07 {
	public static void main(String[] args) {
		int x = -345;
		System.out.println(Main07.reverse(x));
	}
	
	public static int reverse(int x) {
		StringBuilder sb = new StringBuilder(Integer.toString(x));
		StringBuilder sb2 = new StringBuilder("-");
		String str = "";
		if (x >= 0) {
			sb = sb.reverse();
			str = sb.substring(0);
		}else {
			sb = sb2.append(sb.reverse());
			str = sb.substring(0,sb.length()-1);
		}
        return Integer.parseInt(str);
    }
}

StringBuilder:(点击,移动,放大)

Integer:(点击,移动,放大)

 

posted @ 2019-07-24 10:51  gentleKay  阅读(154)  评论(0编辑  收藏  举报