开发者

Can I please get some feedback on this `isPalindrome()` function in C?

I'm writing some useful functions in C. One of them is isPalindrome().

I figured to determine if a number is a palindrome or not, I should...

  • get all digits in an array
  • iterate through with two indexes - start one at 0 and one to the array count
  • increment/decrement the indexes whilst subscripting the array whilst they match and if the array count gets to 0 we have a palindrome (i.e. finishing going through all digits).

I came up with...

int isPalindrome(int num) {

    int places[100];
    int i = 0;
    while (num > 0) {
        places[i++] = num % 10; 
        num /= 10;
    }

    int j = 0;
    while (i >= 0 && places[j++] == places[--i]) {
    }
    return i == -1;

}

Is this generally how it is done?

I'm learning C by myself, and although I can tell when my code compiles and doesn't take all day to work something out, I don't have any expert eyes to tell me if I'm on the 开发者_运维百科right track.

So, any improvements or suggestions on my code?

Thanks very much!


You only have to loop while i > j. Once i <= j, you are just checking all the characters a second time.


Although using inline ++ and -- operators in the following might seem clever:

while (i >= 0 && places[j++] == places[--i]) { 
} 

your code will be easier to read if you put those inside the loop body:

while (i >= 0 && places[j] == places[i-1]) { 
    j++;
    i--;
} 

This way, the reader of the code won't have to think about the possible side effects of changing the values of i and j within the conditional test. There will probably be no measurable effect on the speed of the compiled code (although, if performance is important to this function, you should check with your compiler).

Also, you've got a bug where you will access places[-1] if i == 0.


I'd just use sprintf to "convert the string to digits":

char places[100];
sprintf(places, "%i", num);
i = strlen(places);


In java

static boolean isPalindrome(String p) {
    return p.equals(new StringBuilder(p).reverse().toString());
}

In c++ and c

int IsPalindrome(char *string) {
    int bottom = 0, top;

    top = strlen(string) - 1;
    while(bottom < top && string[bottom] == string[top]) {
        ++bottom;
        --top;
    }
    return (bottom >= top ? 1:0);
}

Note, You need to write itoa function, if you need to do this for a number input. Or use ( link ).

Thats how it is generally done. This would also work for all bases and not only 10.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜