Skip to content

Volume ITechnology

4.0.3 — Working With Digits: Count, Sum, Reverse, Palindrome Number ​

Classic · Easy · LeetCode 9 (Palindrome Number), LeetCode 258 (Add Digits)

All five problems on this page use the digit loop from 4.0.0. n % 10 reads the last digit. n // 10 removes it. Only what you do with each digit changes.

The problem ​

Given a whole number, do each of these:

  1. Count its digits. 4721 has 4.
  2. Add up its digits. 4721 gives 4 + 7 + 2 + 1 = 14.
  3. Reverse it. 4721 becomes 1274.
  4. Say whether it reads the same backwards. 12321 does. 1232 does not.
  5. Keep adding the digits until one digit is left. 4721 gives 14, then 1 + 4 = 5.

The interviewer usually adds: "Do it without converting to a string."

1. Count the digits ​

python
def count_digits(n: int) -> int:
    n = abs(n)          # (1)
    if n == 0:
        return 1        # (2)
    count = 0
    while n > 0:
        count += 1
        n //= 10
    return count

print(count_digits(4721))   # → 4
print(count_digits(0))      # → 1
print(count_digits(-305))   # → 3

(1) The minus sign is not a digit. Remove it first.

(2) Zero has one digit, but the loop would not run at all for it. So handle it on its own.

A one-line version is len(str(abs(n))). Say it, then write the loop anyway, because the loop is what is being tested.

2. Sum of digits ​

python
def digit_sum(n: int) -> int:
    n = abs(n)
    total = 0
    while n > 0:
        total += n % 10     # add the last digit
        n //= 10            # drop the last digit
    return total

print(digit_sum(4721))   # → 14

Zero needs no special case here. The loop does not run, and the sum stays 0, which is correct.

3. Reverse a number ​

This one needs a moment of thought. We read digits from the right. We need to build a new number where each new digit goes on the right end.

How do you add a digit to the right end of a number? Multiply by 10, which shifts every digit one place left and leaves a 0 at the end. Then add the new digit into that empty place. Adding 4 to the end of 127 is 127 \times 10 + 4 = 1274.

python
def reverse_number(n: int) -> int:
    sign = -1 if n < 0 else 1       # (1)
    n = abs(n)
    rev = 0
    while n > 0:
        rev = rev * 10 + n % 10     # (2)
        n //= 10                    # (3)
    return sign * rev

print(reverse_number(4721))   # → 1274
print(reverse_number(-120))   # → -21

(1) Remember the sign and work on the positive number. Put the sign back at the end.

(2) Shift rev left by one place and drop the last digit of n into the gap.

(3) Remove that digit from n.

Trace on 4721:

n beforelast digitrev after
472110 \times 10 + 1 = 1
47221 \times 10 + 2 = 12
47712 \times 10 + 7 = 127
44127 \times 10 + 4 = 1274

Trailing zeros vanish. -120 reverses to -21, not -021. A number cannot start with zero, so the leading 0 of the reverse simply disappears. If the interviewer wants the zero kept, the answer must be a string.

In other languages this can overflow. Reversing 1,999,999,999 gives 9,999,999,991, which does not fit in a 32-bit integer. LeetCode's "Reverse Integer" asks you to return 0 in that case. 4.30.7 solves that version.

4. Palindrome number ​

A palindrome reads the same forwards and backwards. The word comes from Greek, meaning "running back again".

The simple answer: reverse the number and compare.

python
def is_palindrome_number(n: int) -> bool:
    if n < 0:
        return False                 # (1)
    return n == reverse_number(n)

print(is_palindrome_number(12321))   # → True
print(is_palindrome_number(-121))    # → False
print(is_palindrome_number(10))      # → False

(1) A negative number cannot be a palindrome. -121 backwards is 121-, and the minus sign is now at the wrong end.

The half-reverse trick. You only need to reverse half the number. Keep moving digits from n into rev until rev is at least as big as what is left of n. Then you have reached the middle.

python
def is_palindrome_half(n: int) -> bool:
    if n < 0 or (n % 10 == 0 and n != 0):   # (1)
        return False
    rev = 0
    while n > rev:                           # (2)
        rev = rev * 10 + n % 10
        n //= 10
    return n == rev or n == rev // 10        # (3)

print(is_palindrome_half(1221))    # → True
print(is_palindrome_half(12321))   # → True
print(is_palindrome_half(1230))    # → False

(1) A number ending in 0 would have to start with 0 to be a palindrome. Only 0 itself does that. Without this line, 10 would wrongly pass. The first step moves the 0 into rev, so rev stays 0 and n becomes 1. The second step moves the 1, so rev becomes 1 and n becomes 0. Now line (3) checks 0 == 1 // 10, which is 0 == 0, and says True. The leading zero of the reverse has vanished, which is exactly the problem.

(2) Stop when rev catches up with what is left of n.

(3) Even length: the two halves match exactly. For 1221, we stop at n = 12, rev = 12. Odd length: the middle digit ended up in rev, so drop it with // 10. For 12321, we stop at n = 12, rev = 123, and 123 // 10 is 12.

This version does half the work. It also matters in languages with fixed-size integers, because the full reverse of a large number can overflow, while half of it never can.

5. Digital root: add the digits until one is left ​

python
def digital_root_loop(n: int) -> int:
    while n >= 10:
        n = digit_sum(n)
    return n

print(digital_root_loop(4721))   # → 5

That works, but there is a well-known shortcut with no loop at all.

python
def digital_root(n: int) -> int:
    if n == 0:
        return 0
    return 1 + (n - 1) % 9

print(digital_root(4721))   # → 5
print(digital_root(9))      # → 9

Why this works. The number 10 is 1 more than 9. So 10 \bmod 9 = 1, and 100 \bmod 9 = 1, and every power of 10 leaves remainder 1 when divided by 9. Now write 4721 = 4 \times 1000 + 7 \times 100 + 2 \times 10 + 1. Divide each part by 9. Each power of 10 acts like a 1. So 4721 leaves the same remainder as 4 + 7 + 2 + 1.

In plain words: a number and the sum of its digits leave the same remainder when divided by 9. Adding digits again and again never changes that remainder. So the final single digit is just the remainder after dividing by 9. There is one adjustment. When the remainder is 0 (for 9, 18, 27 and so on) the digital root is 9, not 0. The formula 1 + (n - 1) % 9 handles that. It shifts the range down by one, takes the remainder, then shifts back up, so the answers run from 1 to 9 instead of 0 to 8.

This fact is centuries old. Accountants used it as casting out nines to check sums by hand long before calculators. It is also why "a number is divisible by 9 exactly when its digit sum is divisible by 9".

Complexity ​

The loops each run once per digit, which is O(\log n) time. The half-reverse runs half as many steps. The digital-root formula is O(1). All of them use O(1) memory.

What the interviewer will push on ​

These are the questions that usually come right after you solve it. Each one has a short, plain answer you can say out loud.

"Can you do it without turning the number into a string?" Yes. Use the digit loop. n % 10 gives the last digit, and n // 10 removes it. Repeat until n is 0.

"What about 0 and negative numbers?" 0 has one digit, so count-digits needs a special case for it. For negative numbers, work on abs(n) and put the sign back at the end. A negative number is never a palindrome, because the minus sign is only at the front.

"Can reversing a number overflow?" Not in Python. In Java or C it can. Reversing 1,999,999,999 gives 9,999,999,991, which is too big for a 32-bit integer. The half-reverse method avoids this, because half of a number is always small enough.

"Can you find the digital root without a loop?" Yes: 1 + (n - 1) % 9, with 0 giving 0. It works because a number and the sum of its digits always leave the same remainder when divided by 9.

One thing to volunteer: "The digit-sum rule for checking divisibility by 9 comes from the same fact as the digital-root formula."

Next: 4.0.4 Armstrong, Perfect and Strong Numbers. More digit loops, plus a faster way to find divisors.

Combine chapters into one PDF

Pick the chapters you want. They print in the order you pick them.

Volume I — Technology
Part 0 — Retention & Notation
Part 1 — Foundations of Computation
Part 2 — Operating Systems
2.1 The Kernel
2.2 Processes
2.3 Threads & Scheduling
2.4 Concurrency Under the Hood
2.5 Memory Management
2.6 File Systems
2.7 Input/Output
2.8 Linux for Engineers
2.9 Windows & macOS in Practice
Part 3 — Languages, Compilers & Runtimes
3.6 JavaScript & V8
3.7 TypeScript
3.8 Node.js Internals
3.13 Python & CPython
3.14 FastAPI & Production Python
Part 4 — Data Structures & Algorithms
4.0 Classic Problems — Before NeetCode
4.4 Arrays & Hashing — Problems
4.5 Two Pointers
4.6 Sliding Window
4.8 Stack — Problems
4.9 Linked List — Problems
4.11 Binary Search — Problems
4.13 Trees
4.14 Tree — Problems
4.15 Trie — Problems
4.17 Heap — Problems
4.18 Backtracking — Problems
4.19 Graphs
4.20 Graph — Problems
4.21 Advanced Graph — Problems
4.23 1-D DP — Problems
4.24 2-D DP — Problems
4.26 Greedy — Problems
4.27 Interval — Problems
4.28 Math & Geometry — Problems
4.30 Bit Manipulation — Problems
Part 5 — Networking & the Web
5.3 IP
5.4 Transport
5.6 HTTP
Part 6 — Frontend Engineering
6.1 Browser Internals
6.2 HTML & CSS Mastery
6.3 JavaScript in the Browser
6.4 React, from First Component to Full Shop
6.5 Frameworks & Rendering
6.8 UI Engineering & Patterns
Part 7 — Databases & Storage
7.2 SQL Mastery
7.3 Storage Engine Internals
7.4 Transactions
7.5 NoSQL Taxonomy
7.8 Analytics & Big Data
Part 8 — Security, Identity & Cryptography
8.2 Cryptography
8.3 Protocols of Trust
8.4 Identity: AuthN & AuthZ
8.5 Application Security
8.6 Infrastructure Security
Part 9 — Software Design (LLD)
9.2 OOP Foundations
9.3 Design Principles
9.4 Design Patterns
9.5 Concurrency
9.6 API Design
9.7 LLD Interview Machines
9.9 Node/Express Production Playbook
Part 10 — Distributed Systems & HLD
10.7 Consistency & Consensus
10.8 Messaging & Microservices
10.14 Caching
Building blocks from the design seat
Part 11 — System Design Case Studies
Part 12 — AI & ML Engineering
12.1 What AI Engineering Is
12.2 The Math You Need
12.3 Classical Machine Learning
12.4 Data for ML
12.5 Deep Learning
12.6 Embeddings & Vector Search
12.7 Transformers & LLMs
12.8 Building with LLMs
12.9 Retrieval-Augmented Generation
12.10 Agents
12.11 Adapting Models
12.12 Production AI
12.13 Multimodal AI
12.14 AI Security & Governance
12.15 Case Studies & Capstone
Part 13 — Cloud, DevOps & Infrastructure
13.11 Git, from First Commit to Team Workflow
Part 14 — Containers: Docker & Kubernetes
14.1 Foundations
14.2 Docker
14.3 Kubernetes
14.4 Kubernetes on Azure
Part 15 — The Craft & Career
Nothing picked yet