Reverse Number in C++: Naive, Loop, and String Methods

Reverse Number is a staple interview problem: given a non-negative integer N, output the integer obtained by writing its digits in the opposite order. The task reinforces integer arithmetic, string handling, and edge-case thinking.

🔹 Problem Statement

Input: A single non-negative integer N (0 ≤ N ≤ 1018).
Output: The number obtained by reversing the decimal digits of N.

Examples: N = 123 → 321, N = 1200 → 21 (leading zeros vanish), N = 0 → 0.

🔹 Naive Positional Extraction : Reverse Number in C++

Compute each digit’s position with powers of ten—conceptually simple but slower (O(d2)).

#include <iostream>
#include <cmath>
using i64 = long long;
int main() {
    i64 n; std::cin >> n;
    if (n == 0) { std::cout << 0; return 0; }
    int digits = static_cast
    (std::floor(std::log10(n))) + 1; // d
    i64 rev = 0;
    for (int i = 0; i < digits; ++i) {
        int last = n % 10;   // current least-significant digit
        n /= 10;             // drop it
        rev += last * static_cast
        (std::pow(10, digits - 1 - i));
    }
    std::cout << rev;
}

📝 Dry-Run (N = 123)


d = 3, rev = 0
loop 0: last = 3, rev += 3·102 → 300
loop 1: last = 2, rev += 2·101 → 320
loop 2: last = 1, rev += 1·100 → 321 ✅

Time: O(d2) (because pow is O(1) but inside a loop and many CPUs implement it iteratively).
Space: O(1)
Educational yet inefficient.

🔹 Why Computing Each Digit’s Position with Powers of Ten Can Be O(d²)

Please follow these step by step guide. Let’s walk through the reasoning step by step with examples and a dry run.

👉 Step 1: Identify the Loop


The loop runs d = digits times. Each iteration performs:

  • n % 10 → O(1)
  • n / = 10 → O(1)
  • std::pow(10, digits - 1 - i) → potentially costly

👉 Step 2: Analyze std::pow


For integer exponents, std::pow(base, exponent) is not guaranteed to be O(1). A naive implementation multiplies base by itself exponent times → O(exponent).

👉 Step 3: Count Total Operations


Loop iteration i computes pow(10, d-1-i). Number of multiplications = d-1-i. Sum over all iterations:

0 + 1 + 2 + … + (d-1) = d(d-1)/2 ≈ O(d²)

📝 Dry Run (N = 123, d = 3)


Looplastpow(10, d-1-i)rev updaterev final
0310² = 1000 + 3*100300
1210¹ = 10300 + 2*10320
2110⁰ = 1320 + 1*1321

Here, each iteration computes a power, and if pow is naive, the cost grows linearly with the exponent → total O(d²).

⚡ Optimized O(d) Approach


i64 rev = 0, multiplier = 1;
for (int i = 0; i < digits; ++i) {
    int last = n % 10;
    n /= 10;
    rev += last * multiplier;
    multiplier *= 10;   // build power iteratively
}

Now, multiplier is updated in O(1) each iteration, giving guaranteed O(d) time complexity.

✅ Summary


  • Original code can be O(d²) if std::pow is naive.
  • Optimized approach using iterative multiplication is O(d).

🔹 Efficient Loop Method : Reverse Number in C++

Build the reversed number digit-by-digit—classic, clean, and optimal for integers. ⚡

#include <iostream>
using i64 = long long;
int main() {
    i64 n; std::cin >> n;
    i64 rev = 0;
    do {                        // handles n = 0, too
        int digit = n % 10;     // extract last digit
        rev = rev * 10 + digit; // push digit to rev
        n /= 10;                // drop last digit
    } while (n != 0);
    std::cout << rev;
}

📝 Dry-Run (N = 1200)


rev = 0
step 1: digit = 0 → rev = 0, n = 120
step 2: digit = 0 → rev = 0, n = 12
step 3: digit = 2 → rev = 2, n = 1
step 4: digit = 1 → rev = 21, n = 0 → stop. Output 21 ✅

Time: O(d) (≤ 18 for 64-bit).
Space: O(1)
Fastest arithmetic approach and interviewer favorite.

🔹 String Convert + std::reverse : Reverse Number in C++

Leverage the STL: read as a string, reverse the characters, then convert back to integer.

#include <iostream>
#include <string>
#include <algorithm>
int main() {
     // accepts leading zeros
    std::string s; std::cin >> s;
    // reverse in-place
    std::reverse(s.begin(), s.end()); 
    // strip leading zeros
    std::size_t pos = s.find_first_not_of('0'); 
    std::string trimmed = (pos == std::string::npos) 
    ? "0" : s.substr(pos);
    std::cout << trimmed;
}

📝 Dry-Run (N = 987654)


Read "987654" → reverse → "456789" → no leading zeros → print 456789 ✅

Time: O(d)
Space: O(d) (string buffer)
Very readable; sometimes disallowed in strict coding competitions.

🔹 Takeaways

  • Discuss a slow baseline first (positional extraction) to show thought process.
  • The loop method is optimal (O(d) time, O(1) space) and handles any 64-bit integer.
  • String reversal is concise but costs extra memory and skips arithmetic practice.
  • Watch for leading zeros: they disappear in the numeric result by definition.
  • Mention potential 32-bit overflow if interviewer extends range; use 64-bit variables.

📝 Try it Yourself: Adapt the loop method to reverse a number in any base B (2 ≤ B ≤ 16). Which two operators need to change?

Mastering this problem teaches incremental optimization, edge-case handling, and clear code documentation—skills that recur in tougher algorithmic interviews.

Leave a Comment

About RadiantRiva

Your go-to resource for coding tutorials, developer guides, and programming tips.

Learn More

Quick Links

Follow Us

Newsletter

Get coding tips, tutorials, and updates straight to your inbox.