Tuesday, October 9, 2012

Code for reversing the digits of a given integer

Recently while browsing and I found one interesting question to reverse the digit of given integer. I thought to solve the same.

Solution is quite simple then I initially thought. Following is my solution.
    
    int origNum = 12304;
    int reverseNum = 0;

    while( origNum != 0) {
        int lastDigit = origNum % 10;
        origNum /= 10;
        reverseNum = reverseNum * 10;
        reverseNum = reverseNum + lastDigit;
    }

    printf("reverse number %d", reverseNum);

2 comments:

  1. Beware of a possible overflow in the reversed number. You could use long long type for the result, because the result may be bigger what int type can represent.

    ReplyDelete