[LeetCode # 9: palindrome C language

Recently ability to write code intended to practice, so start with a simple question to do.
Most still use the C language to solve.
@(solution)

topic

Determine whether an integer is a palindrome. Palindrome correct order (from left to right) and reverse (right to left) reading is the same integer.

Example 1:
Input: 121
Output: true
Example 2:
Input: -121
Output: false
interpretation: read from left to right, -121. Reading from right to left, as 121-. So it is not a palindrome number.
Example 3:
Input: 10
Output: false
interpretation: reading from right to left, to 01. So it is not a palindrome number.

Specific links https://leetcode-cn.com/problems/palindrome-number/

Thinking

This is similar to # 7, but need to consider the efficiency of the method.

Preliminary ideas

The initial idea is to use a while loop, which in circulation and reverse resolve to take more than the sum of the work. And then after a cycle comparing inclusive.

Specific code as follows:

bool isPalindrome(int x) {
    if (x < 0 || x%10 == 0 && x != 0) return 0;
    if (x / 10 == 0) return 1;
    int a[20] = { 0 }, n = 0;
    while (x) {
        a[n] = x % 10;
        x = x / 10; 
        n++;
    }

    for (int i = 0; i < n / 2; i++){
        if (a[i] != a[n-1-i]) return 0; 
    }
    return 1;
}

It should be noted that we can advance the data to determine, for example, it is not necessarily negative palindromic number, the last digit is non-zero number 0 is certainly not a palindrome number, only one figure must be a palindrome. ,

Further ideas

After seeing the official explanations, mention the number itself reversed, then the number after the reversal compared to the original figures, if they are the same, then this number is a palindrome.

bool isPalindrome(int x) {
    if (x < 0 || x%10 == 0 && x != 0) return 0;
    if (x / 10 == 0) return 1;
    int rev = 0;
    while (x > rev) {
        rev = x % 10 + rev * 10;
        x = x / 10; 
    }
    return x == rev || x == rev / 10;
}

Note that x is not known in advance due to the odd bit or even bits, so the final appeared a comparison condition x == rev / 10.

Finally idea

There are also mentioned in the title convert a number to a string, I started to think of using itoa, but leetcode does not support this function, so use sprintf to convert.

bool isPalindrome(int x) {
    if (x < 0 || x % 10 == 0 && x != 0) return 0;
    char a[20] = { 0 };
    sprintf_s(a,"%d",x);

    for (int i = 0; i< (strlen(a) / 2); i++){
        if (a[i] != a[strlen(a) - 1 - i]) return 0;
    }
    return 1;
}

Reference links

http://www.cnblogs.com/sddai/p/5774121.html
https://blog.csdn.net/xiaotaiyangzuishuai/article/details/79205773

to sum up

On the simple question, not only to note that the solution to the problem, but also pay attention to the efficiency of the method, try to use a variety of methods to solve.

Guess you like

Origin www.cnblogs.com/dasbeste/p/11128761.html