Practice › Basics
Reverse a Number
Easy · Basics · Asked at TCS, Infosys, Wipro, Accenture, Cognizant
Reverse the digits of a non-negative integer n. Leading zeros of the result are dropped (so 1200 becomes 21).
Input
One integer n.
Output
The reversed number.
Constraints
- 0 ≤ n ≤ 10^9
Example 1
Input
1234
Output
4321
Example 2
Input
1200
Output
21
Hints
- n % 10 gives the last digit and n / 10 removes it.
- Build the answer as rev = rev * 10 + digit. Leading zeros disappear on their own.
Approach
Peel off digits from the right with % 10 and push them onto the result with rev * 10 + digit. Zeros at the end of n become leading zeros of rev, which simply don't show up (1200 → 0, 0, 2, 1 → 21). The reverse of a 10-digit number can exceed 32 bits, so use a 64-bit result.
Complexity: O(number of digits) time · O(1) space
Solution
C++ solution
#include <bits/stdc++.h>
using namespace std;
int main() {
long long n, rev = 0;
cin >> n;
while (n > 0) {
rev = rev * 10 + n % 10;
n /= 10;
}
cout << rev << "\n";
return 0;
}Python solution
n = int(input())
rev = 0
while n > 0:
rev = rev * 10 + n % 10
n //= 10
print(rev)Java solution
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
long n = sc.nextLong(), rev = 0;
while (n > 0) {
rev = rev * 10 + n % 10;
n /= 10;
}
System.out.println(rev);
}
}