Problem Solving: Reverse, Palindrome, and Binary Conversion
Learn to write programs to find the reverse of a number, determine whether a number is a palindrome or not, and determine the binary representation of a decimal number.
We'll cover the following
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
.
Implementation
Here are the further implementation details:
- To get the last digit of
num
, we’ill take the modulus of thenum
by10
. For example ifnum
has12345
thennum%10
will give us5
. We can store that as arem
.
rem = num % 10; // rem = 5
- Now, we want to store the reverse of
num
inm
, which is initially zero. We’ll multiplym
with10
and addrem
inm
.
m = (m*10)+rem; //m = 5 (0x10+5)
- We have
5
in them
variable. In the next iteration, we need1234
instead of12345
, so we’ll dividenum
by10
.
num = num / 10; // Now we have num = 1234 (12345/10)
- We’ll repeat all these steps until
num
equals0
. We’ll do this in a function and we will call itreverse()
.
Let’s write the complete code and see the output:
Get hands-on with 1200+ tech skills courses.