β Back to Revisions
Day 13
View Problem βCount Digits and Reverse Number
π
November 6, 2025π·οΈ TakeUForward
Complexity Analysis
Brute Force
N/A
Optimized
N/A
Space
N/A
Solutions
Pythonπ
import sys
def solve_digit_manipulation():
try:
N = int(sys.stdin.readline().strip())
except:
return
original_n = N
# Handle negative numbers by converting to positive for digit logic
num = abs(N)
# --- 1. Count Digits ---
temp_count = num
count = 0
while temp_count > 0:
temp_count //= 10
count += 1
print(f"Count: {count}")
# --- 2. Reverse Number ---
temp_reverse = num
reversed_num = 0
while temp_reverse > 0:
last_digit = temp_reverse % 10
reversed_num = reversed_num * 10 + last_digit
temp_reverse //= 10
# Apply original sign
if original_n < 0:
reversed_num *= -1
print(f"Reversed: {reversed_num}")
if __name__ == "__main__":
solve_digit_manipulation()Javaβ
import java.util.Scanner;
class Solution {
// O(log N) Time, O(1) Space
public static void solve_digit_manipulation() {
Scanner scanner = new Scanner(System.in);
if (!scanner.hasNextLong()) return;
long N = scanner.nextLong();
long originalN = N;
long num = Math.abs(N);
// --- 1. Count Digits ---
long tempCount = num;
int count = 0;
if (num == 0) {
count = 1;
} else {
while (tempCount > 0) {
tempCount /= 10;
count++;
}
}
System.out.println("Count: " + count);
// --- 2. Reverse Number ---
long tempReverse = num;
long reversedNum = 0;
while (tempReverse > 0) {
int lastDigit = (int)(tempReverse % 10);
reversedNum = reversedNum * 10 + lastDigit;
tempReverse /= 10;
}
if (originalN < 0) {
reversedNum *= -1;
}
System.out.println("Reversed: " + reversedNum);
scanner.close();
}
public static void main(String[] args) {
solve_digit_manipulation();
}
}C++β‘
#include <iostream>
#include <algorithm>
using namespace std;
// O(log N) Time, O(1) Space
void solve_digit_manipulation() {
long long N;
if (!(cin >> N)) return;
long long original_n = N;
long long num = abs(N);
// --- 1. Count Digits ---
long long temp_count = num;
int count = 0;
if (num == 0) { // Edge case: count is 1 for number 0
count = 1;
} else {
while (temp_count > 0) {
temp_count /= 10;
count++;
}
}
cout << "Count: " << count << endl;
// --- 2. Reverse Number ---
long long temp_reverse = num;
long long reversed_num = 0;
while (temp_reverse > 0) {
int last_digit = temp_reverse % 10;
// Important: check for overflow here in production code
reversed_num = reversed_num * 10 + last_digit;
temp_reverse /= 10;
}
if (original_n < 0) {
reversed_num *= -1;
}
cout << "Reversed: " << reversed_num << endl;
}
int main() {
solve_digit_manipulation();
return 0;
}Tags
mathdigitstraversal
π‘ Revision Tips
- β’ Try solving from memory before checking your solution
- β’ Focus on the approach and pattern, not just the code
- β’ Can you explain the solution to someone else?
- β’ Try implementing in a different language