palindrome function

Jonathan M Davis jmdavisprog at gmail.com
Sat Aug 7 18:38:41 PDT 2010


As a side note, I'd suggest making your function take a string of some kind, if 
not outright making it a template to deal with multiple string types. That way, 
you can check for a palindrome regardless of whether you're dealing with 
numbers, and if you need to do it with a number, you just convert it to a string 
when you call isPalidrome. So, you're function (without changing anything other 
than the signature) would become something like

bool isPalindrome(S)(in S s) {
    int length = s.length;
    int limit = length / 2;
    for (int i = 0; i < limit; ++i) {
        if (s[i] != s[$ - 1 - i]) {
            return false;
        }
    }
    return true;
}


and my version would look like this:

bool isPalindrome(S)(in S s)
{
    while(!s.empty)
    {
        if(s.length == 1)
            return true;

        if(s.front != s.back)
            return false;

        s.popFront();
        s.popBack();
    }

    return true;
}


So, calls to it with a number would look like

isPalindrome(to!string(num))

- Jonathan M Davis


More information about the Digitalmars-d-learn mailing list