1.

Write a program that reverses a given input number.

Answer»

EXAMPLE

Input: 

1234

Output: 

4321

Approach:

We follow a greedy approach. We start extracting each DIGIT from the original number from the end and keep on ADDING it at the end of the new number, thereby reversing the given number.

Code:

#include <bits/stdc++.h>using namespace STD;//function to find the reverse of the given inputint reverseNumber(int original_number){ int new_number = 0; while (original_number > 0) { new_number = new_number * 10 + original_number % 10; // extracting the last digit from the original number and appending it to the new number original_number = original_number / 10; } return new_number;}int main(){ int original_number = 1234; cout << "The original number is " << original_number << "\n"; cout << "The reversed number is " << reverseNumber(original_number) << "\n"; return 0;}

Output :

The original number is 1234The reversed number is 4321

Explanation :

In the above code, the function reverseNumber TAKES the input of an integer number and returns the reverse of the number. We extract each digit from the end and append it to the new number.



Discussion

No Comment Found