Palindrome Number(判断一个整数是否是回文串) leetcode9

古城微笑少年丶 2022-05-24 00:23 227阅读 0赞

Determine whether an integer is a palindrome. An integer is a palindrome when it reads the same backward as forward.

Example 1:

  1. Input: 121
  2. Output: true

Example 2:

  1. Input: -121
  2. Output: false
  3. Explanation: From left to right, it reads -121. From right to left, it becomes 121-. Therefore it is not a palindrome.

Example 3:

  1. Input: 10
  2. Output: false
  3. Explanation: Reads 01 from right to left. Therefore it is not a palindrome.

Follow up:

Coud you solve it without converting the integer to a string?

  1. public boolean isPalindrome(int x) {
  2. if(x<0)
  3. return false;
  4. String res=x+"";
  5. //String res=Integer.toString(x);
  6. //排除‘-’的回文串
  7. //if(res.charAt(0)=='-')
  8. //res=res.substring(1);
  9. int middle=res.length()/2;
  10. if(res.length()%2==0){
  11. for(int i=middle-1,j=middle;i>=0&&j<res.length();){
  12. if(res.charAt(i--)!=res.charAt(j++))
  13. return false;
  14. }
  15. }else{
  16. for(int i=middle-1,j=middle+1;i>=0&&j<res.length();){
  17. if(res.charAt(i--)!=res.charAt(j++))
  18. return false;
  19. }
  20. }
  21. return true;
  22. }

发表评论

表情:
评论列表 (有 0 条评论,227人围观)

还没有评论,来说两句吧...

相关阅读