Power button - integer reversal (java)

Disclaimer: This article is a blogger original article, follow the CC 4.0 BY-SA copyright agreement, reproduced, please attach the original source link and this statement.
This link: https://blog.csdn.net/lc5801889/article/details/89497345

Title: integer reversal

Gives a 32-bit signed integer, you need this integer number on each inverted.

Example 1:

Input: 123
Output: 321

Example 2:

Input: -123
Output: -321

Example 3:

Input: 120
Output: 21

Note:
Suppose we have an environment can store the 32-bit signed integer, then the value range of [-231 231--1]. Please According to this hypothesis, if integer overflow after reverse it returns 0.
Outline of Solution:
This problem mainly on the integer inversion operation, to be noted that the numerical range [-231 231--1], that is, the result must be inverted between 2147483647-2147483648, outputs 0 otherwise. Here I used a StringBuffer in Java class that provides reverse the string class methods, the first integer conversion inversion operation after the string is then converted back to integer output.
code show as below:

class Solution {
    public int reverse(int x) {      
    	long ret = 0;
    	long min = -2147483648;
    	long max = 2147483647;//定义数值范围
    	StringBuffer sb = new StringBuffer();
    	sb.append(x);//将该变量添加到StringBuffer类中
        if(x>0) {  //当变量大于0时直接输出反转后的结果     	
        	sb.reverse();//反转操作
        	for (int i=0;i<sb.length();i++) {
				ret = ret*10+(int)sb.charAt(i)-48;//将反转后的字符串转换为整数
			}
        	if(ret<max){	//超过范围返回0
        		return (int)ret;
        	}else {
        		return 0;
        	}
        }else if(x<0) {//当变量小于0时输出反转后的结果的负数 
        	sb.reverse();
        	for (int i=0;i<sb.length()-1;i++) {
				ret = ret*10+(int)sb.charAt(i)-48;
			}
        	if(0-ret>min){	//超过范围返回0
        		return (int) ((int)0-ret);
        	}else {
        		return 0;
        	}
        }else {
        	return 0;//变量为0时返回0
        }
    }
}

! [Insert Picture description here] (https://img-blog.csdnimg.cn/20190424164547787.png

Guess you like

Origin blog.csdn.net/lc5801889/article/details/89497345