Reverse Integer && Palindrome Number-LeetCode

1.Reverse Integer

Reverse digits of an integer.

Example1: x = 123, return 321
Example2: x = -123, return -321

click to show spoilers.

Note:

The input is assumed to be a 32-bit signed integer. Your function should return 0 when the reversed integer overflows.


2.Palindrome Number

Determine whether an integer is a palindrome. Do this without extra space.

click to show spoilers.

Some hints:

Could negative integers be palindromes? (ie, -1)

If you are thinking of converting the integer to string, note the restriction of using extra space.

You could also try reversing an integer. However, if you have solved the problem "Reverse Integer", you know that the reversed integer might overflow. How would you handle such case?

There is a more generic way of solving this problem.

这俩题基本可以看作是一类的题吧,很相似,所以就写在一起了。

第一题我的解法

遵循题目最基本的设定,将输入整数变换为字符串,再将其反转为新字符串,之后再转为long型整数,判断是否超过int型表示范围。这解法基本没啥创新,完全循规蹈矩,而且用到了比待判断量要更大范围的数据类型,所以并不值得提倡,好在该思路不费脑子实现快。

public class Solution {
	public int reverse(int x) {
		String number=String.valueOf(x);
		long temp=0;
		int loc=0;
		if(number.startsWith("-")){
			loc=1;
			temp=-1;
		}else{
			temp=1;
		}
		number=new StringBuilder(number.substring(loc)).reverse().toString();
		temp*=Long.valueOf(number);
		if(temp<Integer.MAX_VALUE && temp>Integer.MIN_VALUE)return (int)temp;
		else return 0;
	}
}

第一题大神解法

监测反转后数字的溢出,提前结束程序,详见代码注释。

public class Solution {
	public int reverse(int x) {
		int result=0;
		while(x!=0){
			int tear=x%10;			//取x的末位
			int newresult=result*10+tear;	//将末位tear作为首位值,加权计算后赋给newresult
			if(newresult/10!=result){
							//关键步骤,如果在上一步加权计算时,newresult已经溢出那么
							//newresult/10得到的值 和 它十位往上的部分(result)就不会相等,所以提前结束翻转
				return 0;
			}
			result=newresult;
			x/=10;
		}
		return result;
	}
}

第二题解法(借鉴了大神代码):

public class Solution {
    public boolean isPalindrome(int x) {
        int tear=0,temp=x,num=0;
        while(temp>0){
        	tear=temp%10;
        	if((num*10+tear)/10!=num)return false;
        	num=(num*10+tear);
        	temp/=10;
        }
        if(num==x)return true;
        else return false;
    }
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值