Reverse Integer && Palindrome Number-LeetCode

来源:互联网 发布:linux nat映射查看 编辑:程序博客网 时间:2024/05/30 23:44

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作为首位值,加权计算后赋给newresultif(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
原创粉丝点击