zoukankan      html  css  js  c++  java
  • [Leetcode 16] 9 Palindrome Number

    Problem:

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

    Analysis:

    One tricky way to do this is to convert it into string and then use the normal palindrome way to solve the problem. Though it violates the requirement of "no extra space", the online judger won't judge whether we are using extra space or not.

    The normal way is to check from the leftmost and rightmost digit, toward the mid digit. Give special attention to negative numbers

    Code:

    Tricky way:

    View Code

    Normal way:

    View Code
     1 public class Solution {
     2     public boolean isPalindrome(int x) {
     3         // Start typing your Java solution below
     4         // DO NOT write main() function
     5         if (x < 0) return false;
     6         
     7         int base = 1;
     8         while (x / base >= 10) {
     9             base *= 10;
    10         }
    11         
    12         
    13         int left=0, right=0;
    14         while (x > 0) {
    15             left = x / base;
    16             right = x % 10;
    17             
    18             if (left != right)
    19                 return false;
    20             
    21             
    22             x = (x - left*base) / 10;
    23             base /= 100;
    24         }
    25         
    26         return true;
    27     }
    28 }

    Attention:

  • 相关阅读:
    高精度乘除运算优化
    高精度除法
    高精度乘法
    期末考试
    P2341 [HAOI2006]受欢迎的牛[SCC缩点]
    P2002 消息扩散[SCC缩点]
    神奇搜索算法A*
    P3205 [HNOI2010]合唱队[区间dp]
    P4170 [CQOI2007]涂色
    P1220 关路灯[区间dp]
  • 原文地址:https://www.cnblogs.com/freeneng/p/3033934.html
Copyright © 2011-2022 走看看