Converting a Number into a String

It is easy to check whether a string is a palindrome or not: We can check whether the first character and the last one are identical, and then compare the second character and the second one from the end, and so on. If the converted string is a palindrome, the original should also be a palindrome.
This solution can be implemented with the code in Listing 2-6, which converts a number into a string with the library function sprintf.
Listing 2-6. C Code to Verfiy Palindrome Numbers (Version 1)
/* It returns 1 when number is palindrome, otherwise returns 0. */
#define NUMBER_LENGTH 20
int IsPalindrome_solution1(unsigned int number) {
    char string[NUMBER_LENGTH];
    sprintf(string, "%d", number);
    return IsPalindrome(string);
}
int IsPalindrome(const char* const string) {
    int palindrome = 1;
    if(string != NULL) {
        int length = strlen(string);
        int half = length >> 1;
        int i;
        for(i = 0; i < half; ++ i) {
            if(string[i] != string[length - 1 - i]) {
                palindrome = 0;
break; }


}
    return palindrome;
}
Usually, this solution is not the one expected by interviewers. One reason is that while it is intuitive, interviewers expect something innovative, and another reason is that it requires auxiliary memory to store the converted string.
www.cinterviews.com appreciates your contribution please mail us the questions you have to cinterviews.blogspot.com@gmail.com so that it will be useful to our job search community

No comments: