Print all diagonals of a matrix in alternate order
March 9, 2016
Helper Function: Check if character is a digit or not
April 26, 2016

Helper Function: Reverse a Number

Sometimes we need helper functions in our code. One such helper function needed is to reverse a number. i.e a function which returns me ‘321’ if I pass ‘123’ to it. Implement the following function

    int reverseNum(int num)

The function should accept an integer and should return an integer whose digits are reverse of the original number.

Input: 123     Output: 321
Input: 0       Output: 0
Input: 100     Output: 1

Note that the reverse of ‘100’ is ‘1’ because we are dealing with numbers. Had it been strings, the reverse of ‘100’ would have been ‘001’.

Solution:

The code is very simple as shown below.

int reverseNum(int num)
{
    int reverse = 0;
    while(num != 0)
    {
        reverse = reverse*10 + num%10;
        num = num/10;
    }
    return reverse;
}

 

Leave a Reply

Your email address will not be published. Required fields are marked *