We’ll start by finding the reverse of a number. We’ll then use the reverse() function to determine whether a number is a palindrome or not and determine the binary representation of a decimal number.

Reverse of a number

Write a function that takes an input integer from the user and returns the reverse of it.

Sample input

Passed parameter: 12345

Sample output

Returned value: 54321

Here’s the prototype of the required function:

int reverse(int num);

How can we construct a new number which is the reversal of num?

Idea: Reverse of a number

'Chop the number digit by digit from the rightmost position of num and keep appending it to the right of the constructed new number m.


Here are the further implementation details:

  1. To get the last digit of num, we’ill take the modulus of the num by 10. For example if num has 12345 then num%10 will give us 5. We can store that as a rem.
   rem = num % 10; // rem = 5
  1. Now, we want to store the reverse of num in m, which is initially zero. We’ll multiply m with 10 and add rem in m.
m = (m*10)+rem; //m = 5 (0x10+5)
  1. We have 5 in the m variable. In the next iteration, we need 1234 instead of 12345, so we’ll divide num by 10.
num = num / 10; // Now we have num = 1234 (12345/10)
  1. We’ll repeat all these steps until num equals 0. We’ll do this in a function and we will call it reverse().

Let’s write the complete code and see the output:

Get hands-on with 1200+ tech skills courses.