LeetCode-7-Reverse Integer-颠倒整数

英文题目:

Given a 32-bit signed integer, reverse digits of an integer.

Example 1:

Input: 123
Output:  321

Example 2:

Input: -123
Output: -321

Example 3:

Input: 120
Output: 21

Note:
Assume we are dealing with an environment which could only hold integers within the 32-bit signed integer range. For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.


中文题目:

给定一个范围为 32 位 int 的整数,将其颠倒。

例 1:

输入: 123
输出:  321

 

例 2:

输入: -123
输出: -321

 

例 3:

输入: 120
输出: 21

 

注意:

假设我们的环境只能处理 32 位 int 范围内的整数。根据这个假设,如果颠倒后的结果超过这个范围,则返回 0。


代码:

执行用时 28ms

class Solution {
    public int reverse(int x) {
        boolean fuhao=false;
		if(x<0){
			x*=-1;
			fuhao=true;
		}
		String str=Integer.toString(x);
		boolean flag=false;
		long num=0;
		for(int i=str.length()-1;i>=0;i--){
			if(str.charAt(i)!='0'){
				flag=true;
			}
			if(str.charAt(i)=='0'&&flag==false){
				continue;
				}else{
				num+=str.charAt(i)-'0';
				if(i-1!=-1){
					num*=10;
				}
			}
		}
		if(fuhao==false){    //判断是否超出int限制
			if(num>2147483647){
				num=0;
			}
		}else{
			num*=-1;
			if(num<-2147483648){
				num=0;
			}
		}
		return (int)num;
    }
}

发布了11 篇原创文章 · 获赞 5 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/w84963568/article/details/79777933
今日推荐