LeetCode | Easy | Palindrome Number | 팰린드롬

Algorithm 2019. 8. 29. 15:22
반응형

https://leetcode.com/problems/palindrome-number/description/

 

Palindrome Number - LeetCode

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com

 

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

Example 1:

Input: 121 Output: true

Example 2:

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

Example 3:

Input: 10 Output: false 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

입력: 11 

결과 : True

 

테스트 케이스 2

입력 121232121

결과: True

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
using System;
 
namespace Application
{
    class MainClass
    {
        public static void Main(string[] args)
        {
            //Console.WriteLine(5 / 2);
            //Console.WriteLine(5 % 2);
 
            //Console.WriteLine(4 / 2);
            //Console.WriteLine(4 % 2);
 
 
            var sol = new Solution();
            var result = sol.solution(11);
            Console.WriteLine(result);
        }
    }
 
    public class Solution {
        public bool solution(int n) {
            bool answer = false;
 
            var str = n.ToString();
            if (str.Length % 2 == 0)
            {
                //짝수
                int left = -1;
                int right = str.Length;
                while(true) {
                    if(left > right)
                    {
                        answer = true;
                        break;
                    }
 
                    ++left;
                    --right;
 
                    if (!str[left].Equals(str[right])) {
                        answer = false;
                        break;
                    }
                }
            }
            else {
                //홀수
                var mid = str.Length / 2;
 
                var str1 = "";
                var str2 = "";
                for (int i = mid + 1; i < str.Length; i++)
                {
                    str1 += str[i];
                }
 
                for (int i = mid; i > 0; i--)
                {
                    str2 += str[i - 1];
                }
                answer = str1.Equals(str2);
            }
            
 
 
            return answer;
        }
    }
}
 
 
 

 

 

 

Solution


Approach 1: Revert half of the number

Intuition

The first idea that comes to mind is to convert the number into string, and check if the string is a palindrome, but this would require extra non-constant space for creating the string which is not allowed by the problem description.

Second idea would be reverting the number itself, and then compare the number with original number, if they are the same, then the number is a palindrome. However, if the reversed number is larger than \text{int.MAX}int.MAX, we will hit integer overflow problem.

Following the thoughts based on the second idea, to avoid the overflow issue of the reverted number, what if we only revert half of the \text{int}int number? After all, the reverse of the last half of the palindrome should be the same as the first half of the number, if the number is a palindrome.

For example, if the input is 1221, if we can revert the last part of the number "1221" from "21" to "12", and compare it with the first half of the number "12", since 12 is the same as 12, we know that the number is a palindrome.

Let's see how we could translate this idea into an algorithm.

Algorithm

First of all we should take care of some edge cases. All negative numbers are not palindrome, for example: -123 is not a palindrome since the '-' does not equal to '3'. So we can return false for all negative numbers.

Now let's think about how to revert the last half of the number. For number 1221, if we do 1221 % 10, we get the last digit 1, to get the second to the last digit, we need to remove the last digit from 1221, we could do so by dividing it by 10, 1221 / 10 = 122. Then we can get the last digit again by doing a modulus by 10, 122 % 10 = 2, and if we multiply the last digit by 10 and add the second last digit, 1 * 10 + 2 = 12, it gives us the reverted number we want. Continuing this process would give us the reverted number with more digits.

Now the question is, how do we know that we've reached the half of the number?

Since we divided the number by 10, and multiplied the reversed number by 10, when the original number is less than the reversed number, it means we've processed half of the number digits.

 

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
public class Solution {
    public bool IsPalindrome(int x) {
        // Special cases:
        // As discussed above, when x < 0, x is not a palindrome.
        // Also if the last digit of the number is 0, in order to be a palindrome,
        // the first digit of the number also needs to be 0.
        // Only 0 satisfy this property.
        if(x < 0 || (x % 10 == 0 && x != 0)) {
            return false;
        }
 
        int revertedNumber = 0;
        while(x > revertedNumber) {
            revertedNumber = revertedNumber * 10 + x % 10;
            x /= 10;
        }
 
        // When the length is an odd number, we can get rid of the middle digit by revertedNumber/10
        // For example when the input is 12321, at the end of the while loop we get x = 12, revertedNumber = 123,
        // since the middle digit doesn't matter in palidrome(it will always equal to itself), we can simply get rid of it.
        return x == revertedNumber || x == revertedNumber/10;
    }
}
 
 

노오...올랍다..

Complexity Analysis

  • Time complexity : O(\log_{10}(n))O(log10(n)). We divided the input by 10 for every iteration, so the time complexity is O(\log_{10}(n))O(log10(n))

  • Space complexity : O(1)O(1).

반응형
: