leetcode 7&9 : Reverse Integer & Palindrome Number

来源:互联网 发布:人工智能计算机视觉 编辑:程序博客网 时间:2024/04/30 01:36

leetcode 7 :

Reverse digits of an integer.

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

思路:

1.考虑输入的正负。

2.考虑是否越界。


代码:

public class Solution {    public int reverse(int x) {        int flag=0;        long result=0;        if(x<0){            flag=1;            x=-x;        }        int lastDigit=0;        while(x>0){            lastDigit=x-x/10*10;            result=result*10+lastDigit;            x=x/10;        }        if(flag==1){            result=-result;        }        if(result>Integer.MAX_VALUE||result<Integer.MIN_VALUE){         result=0;        }        return (int) result;    }}

leetcode 9 :

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

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.

思路:

1.负数不是回文的。

2.不可以使用额外的空间。

3.可以利用反转的方法,但是要考虑到越界问题。


代码:

public class Solution {   public boolean isPalindrome(int x) {       if(x<0) return false;       else{          long result=0;          int y=x;          int lastDigit=0;            while(y>0){                lastDigit=y-y/10*10;                result=result*10+lastDigit;                y=y/10;            }            if(result>Integer.MAX_VALUE||result<Integer.MIN_VALUE) return false;            else if(result==x) return true;            else return false;        }          }     }


0 0
原创粉丝点击
热门问题 老师的惩罚 人脸识别 我在镇武司摸鱼那些年 重生之率土为王 我在大康的咸鱼生活 盘龙之生命进化 天生仙种 凡人之先天五行 春回大明朝 姑娘不必设防,我是瞎子 科目三老是跑偏怎么办 面试官说你不好怎么办 面试紧张心态调整不过来怎么办 面试官问缺乏经验怎么办 办好入职手续后就想辞职怎么办 新店长入职应该怎么办 刚入职怀孕了辞职店长不同意怎么办 派遣证丢了怎么办补办 出国留学回来怎么办派遣证 报到证坏了一边怎么办 江苏报到证丢了怎么办 河南报到证丢了怎么办 报到证丢失10年怎么办 退休时无派遣证怎么办 档案里没有派遣证怎么办 档案中派遣证丢失怎么办 中专毕业后想读大学该怎么办 软考准考证丢了怎么办 面试薪资要低了怎么办 应聘等通知没有电话回复怎么办 学生信息表里的籍贯不对怎么办? 小学生信息表里的籍贯不对怎么办? 钉钉下班没打卡怎么办 如果在厂里饭卡丢了怎么办 工作上做错了事想辞职怎么办 结婚辞职怀孕感觉做错了怎么办 换新手机了钉钉怎么办 公众号申请链接无效怎么办 指纹打卡机时间调错已打卡怎么办 智慧云平台先锋讲座打不开怎么办 下雨穿套裙工装好冷怎么办 国家债务违约不要国际融资怎么办 欠钱的确还不起怎么办 生完孩孑后手发账握不死手怎么办 工作调动没啥消息怎么办 裁剪刀老是推歪怎么办 衣服上粘胶水了怎么办 衣服钻掉了有胶怎么办 衣服上贴纸掉了怎么办 裤子沾上502胶水怎么办 衣服上沾泡沫胶怎么办