Digit-Based Number Problems

Solve one Java logic problem at a time, then flip for the complete explanation and program.

0/240 Known filtered set
Difficulty
Read Full Guide Question: 1 of 240

Java Logic Development · Chapter 02 Companion Article

Digit-Based Number Problems

Fifteen digit-manipulation problems built around one repeating pattern — number % 10 extracts the last digit and number / 10 removes it. Counting, summing, reversing, extracting, and replacing digits all reuse this same extract-process-remove loop.

Overview

Digit-based number problems teach an important programming pattern: repeatedly extract and process individual digits of an integer. These problems strengthen loop logic, arithmetic operators, condition handling, and number manipulation without depending on strings or collections.

Most digit problems are built around two operations: number % 10 extracts the last digit, and number / 10 removes the last digit using integer division. For example, with number = 5837:

OperationResult
5837 % 107
5837 / 10583
583 % 103
583 / 1058

This extract-process-remove pattern is the foundation of most problems in this chapter.

1. Count Digits in a Number

Concept

Digit counting determines how many decimal digits are present in an integer. Examples: 5837 → 4, 91 → 2, 7 → 1, 0 → 1. The usual arithmetic approach repeatedly divides the number by 10 until nothing remains.

Core Logic

For every loop iteration:

  1. Count the current digit.
  2. Remove the last digit using / 10.
  3. Continue until the number becomes 0.

Java Program

Java
public class CountDigits {
    public static void main(String[] args) {
        int number = 58372;
        int temp = Math.abs(number);
        int count = 0;
        if (temp == 0) {
            count = 1;
        } else {
            while (temp > 0) {
                count++;
                temp /= 10;
            }
        }
        System.out.println("Number of digits: " + count);
    }
}

Output

Output
Number of digits: 5

Dry Run

For 58372:

tempcount
583720
58371
5832
583
54
05

The loop executes once for each digit.

Why the Logic Works

Integer division by 10 removes one decimal digit from the right side. Therefore, counting how many divisions are required to reach 0 gives the number of digits.

Important Edge Cases

Zero

A normal while (number > 0) loop never executes for 0, but zero contains one digit. Handle it separately.

Negative Number

The minus sign is not a digit. Use Math.abs() before counting.

Alternative Using String

int count = String.valueOf(Math.abs(number)).length(); is shorter but does not demonstrate digit-processing logic.

Complexity

  • Time: O(d)
  • Space: O(1)

Here d is the number of digits.

Common Mistakes

  • Returning 0 digits for number 0.
  • Counting the negative sign as a digit.
  • Modifying the original number when it must be used later.

Interview Tip

For logic-development questions, interviewers usually expect the arithmetic / 10 approach rather than converting the number to a string.

2. Sum of Digits

Concept

The sum of digits is obtained by extracting each digit and adding it to an accumulator. Example: 58325 + 8 + 3 + 2 = 18.

Core Logic

Logic
digit = number % 10
sum += digit
number /= 10

Java Program

Java
public class SumOfDigits {
    public static void main(String[] args) {
        int number = 5832;
        int temp = Math.abs(number);
        int sum = 0;
        while (temp > 0) {
            int digit = temp % 10;
            sum += digit;
            temp /= 10;
        }
        System.out.println("Sum of digits: " + sum);
    }
}

Output

Output
Sum of digits: 18

Dry Run

tempdigitsum
583222
58335
58813
5518

Why the Logic Works

The remainder after division by 10 always represents the current last decimal digit. Processing every last digit eventually covers the complete number.

Practical Uses

Digit sums appear in:

  • Digital-root problems
  • Harshad number checks
  • Divisibility logic
  • Checksum-style problems
  • Interview number puzzles

Complexity

  • Time: O(d)
  • Space: O(1)

Common Mistake

Writing sum = digit; instead of sum += digit; — the first statement replaces the previous result rather than accumulating it.

3. Product of Digits

Concept

Instead of adding digits, multiply them together. Example: 2342 × 3 × 4 = 24.

Important Initialization

The accumulator must start with 1. Correct: int product = 1;. Incorrect: int product = 0; — any value multiplied by zero remains zero.

Java Program

Java
public class ProductOfDigits {
    public static void main(String[] args) {
        int number = 234;
        int temp = Math.abs(number);
        int product = temp == 0 ? 0 : 1;
        while (temp > 0) {
            int digit = temp % 10;
            product *= digit;
            temp /= 10;
        }
        System.out.println("Product of digits: " + product);
    }
}

Output

Output
Product of digits: 24

Dry Run

tempdigitproduct
23444
23312
2224

Special Case: Digit Zero

For 205, the product becomes 2 × 0 × 5 = 0. Once a zero digit is encountered, the final product must be zero.

Complexity

  • Time: O(d)
  • Space: O(1)

Interview Tip

Pay attention to accumulator initialization. Sum problems normally begin with 0, while product problems normally begin with 1.

4. Reverse a Number

Concept

Reversing a number places its digits in opposite order. Example: 1234554321. The standard formula is reverse = reverse * 10 + digit.

Java Program

Java
public class ReverseNumber {
    public static void main(String[] args) {
        int number = 12345;
        int temp = Math.abs(number);
        int reverse = 0;
        while (temp > 0) {
            int digit = temp % 10;
            reverse = reverse * 10 + digit;
            temp /= 10;
        }
        if (number < 0) {
            reverse = -reverse;
        }
        System.out.println("Reversed number: " + reverse);
    }
}

Output

Output
Reversed number: 54321

Dry Run

tempdigitreverse
1234555
1234454
1233543
1225432
1154321

Why Multiply by 10?

Suppose the current reverse is 54 and the next digit is 3:

Logic
54 * 10 = 540
540 + 3 = 543

Multiplication by 10 creates space for the new last digit.

Trailing Zero Behavior

1200 becomes 21, not 0021. An integer cannot preserve leading zeros.

Integer Overflow

A reversed value can exceed the int range even when the original value is valid. For production-quality code, use long or perform an overflow check before reverse * 10 + digit.

Complexity

  • Time: O(d)
  • Space: O(1)

Common Mistake

Using reverse += digit; — this only adds digits and does not construct the reversed number.

5. First Digit of Number

Concept

The first digit is the leftmost digit. Example: 58374 → 5. Unlike the last digit, there is no direct % 10 operation for the first digit.

Division-Based Logic

Repeatedly divide by 10 until only one digit remains.

Java Program

Java
public class FirstDigit {
    public static void main(String[] args) {
        int number = 58374;
        int temp = Math.abs(number);
        while (temp >= 10) {
            temp /= 10;
        }
        System.out.println("First digit: " + temp);
    }
}

Output

Output
First digit: 5

Dry Run

Output
58374
5837
583
58
5

When the value becomes smaller than 10, only its first digit remains.

Alternative Mathematical Approach

For a positive number: firstDigit = number / 10^(digits - 1). The repeated-division solution is usually simpler and easier to reason about.

Complexity

  • Time: O(d)
  • Space: O(1)

6. Last Digit of Number

Concept

The last digit is the rightmost decimal digit. The modulo operator makes this one of the simplest digit problems.

Formula

Logic
lastDigit = number % 10

Java Program

Java
public class LastDigit {
    public static void main(String[] args) {
        int number = 58374;
        int lastDigit = Math.abs(number % 10);
        System.out.println("Last digit: " + lastDigit);
    }
}

Output

Output
Last digit: 4

Why % 10 Works

Any integer can be written as number = quotient * 10 + remainder. The remainder must be between 0 and 9, which is exactly the last digit.

Examples

NumberLast Digit
583744
1000
77

Complexity

  • Time: O(1)
  • Space: O(1)

7. Sum of First and Last Digit

Concept

This problem combines two earlier operations: extract the last digit using % 10, and find the first digit using repeated division. Example: for 58374, first digit = 5, last digit = 4, sum = 9.

Java Program

Java
public class SumFirstLastDigit {
    public static void main(String[] args) {
        int number = 58374;
        int temp = Math.abs(number);
        int lastDigit = temp % 10;
        while (temp >= 10) {
            temp /= 10;
        }
        int firstDigit = temp;
        int sum = firstDigit + lastDigit;
        System.out.println("First digit: " + firstDigit);
        System.out.println("Last digit: " + lastDigit);
        System.out.println("Sum: " + sum);
    }
}

Output

Output
First digit: 5
Last digit: 4
Sum: 9

Single-Digit Number

For 7: first digit = 7, last digit = 7, sum = 14. Whether this is expected depends on the problem definition.

Complexity

  • Time: O(d)
  • Space: O(1)

Interview Tip

Clarify the expected behavior for single-digit input before writing the solution if the specification is ambiguous.

8. Largest Digit in Number

Concept

Scan every digit while maintaining the largest value encountered so far. Digits can only range from 0 to 9.

Java Program

Java
public class LargestDigit {
    public static void main(String[] args) {
        int number = 583274;
        int temp = Math.abs(number);
        int largest = 0;
        while (temp > 0) {
            int digit = temp % 10;
            if (digit > largest) {
                largest = digit;
            }
            temp /= 10;
        }
        System.out.println("Largest digit: " + largest);
    }
}

Output

Output
Largest digit: 8

Dry Run

Digits are processed as 4, 7, 2, 3, 8, 5:

digitlargest
44
77
27
37
88
58

Possible Optimization

If the largest digit becomes 9, scanning can stop because no decimal digit can exceed 9.

Java
if (largest == 9) {
    break;
}

Complexity

  • Time: O(d)
  • Space: O(1)

Common Mistake

Comparing the complete remaining number instead of the extracted digit. Correct: if (digit > largest)

9. Smallest Digit in Number

Concept

Track the minimum digit encountered while scanning the number. Since decimal digits range from 0 to 9, initialize the minimum to 9.

Java Program

Java
public class SmallestDigit {
    public static void main(String[] args) {
        int number = 583274;
        int temp = Math.abs(number);
        int smallest = temp == 0 ? 0 : 9;
        while (temp > 0) {
            int digit = temp % 10;
            if (digit < smallest) {
                smallest = digit;
            }
            temp /= 10;
        }
        System.out.println("Smallest digit: " + smallest);
    }
}

Output

Output
Smallest digit: 2

Why Initialize with 9?

Every decimal digit is less than or equal to 9, making it a safe starting maximum. Initializing with 0 would fail for positive numbers because no digit can be smaller than zero.

Optimization

If 0 is found, no smaller decimal digit exists:

Java
if (smallest == 0) {
    break;
}

Complexity

  • Time: O(d)
  • Space: O(1)

10. Count Even Digits

Concept

A digit is even when digit % 2 == 0. The even decimal digits are 0, 2, 4, 6, 8.

Java Program

Java
public class CountEvenDigits {
    public static void main(String[] args) {
        int number = 583264;
        int temp = Math.abs(number);
        int count = 0;
        if (temp == 0) {
            count = 1;
        } else {
            while (temp > 0) {
                int digit = temp % 10;
                if (digit % 2 == 0) {
                    count++;
                }
                temp /= 10;
            }
        }
        System.out.println("Even digits: " + count);
    }
}

Output

Output
Even digits: 3

Explanation

Digits: 5, 8, 3, 2, 6, 4. Even digits: 8, 2, 6, 4. Actually, there are 4 even digits. Therefore, the correct output for the program is:

Output
Even digits: 4

This type of manual verification is important when testing digit problems.

Zero Case

The number 0 itself contains one even digit because 0 % 2 == 0.

Complexity

  • Time: O(d)
  • Space: O(1)

11. Count Odd Digits

Concept

A digit is odd when digit % 2 != 0. Odd decimal digits are 1, 3, 5, 7, 9.

Java Program

Java
public class CountOddDigits {
    public static void main(String[] args) {
        int number = 583264;
        int temp = Math.abs(number);
        int count = 0;
        while (temp > 0) {
            int digit = temp % 10;
            if (digit % 2 != 0) {
                count++;
            }
            temp /= 10;
        }
        System.out.println("Odd digits: " + count);
    }
}

Output

Output
Odd digits: 2

Dry Run

Digits: 4, 6, 2, 3, 8, 5. Odd digits: 3, 5. Count = 2.

Relationship with Total Digits

For normal positive integers: evenDigitCount + oddDigitCount = totalDigitCount. This is useful for validating a solution.

Complexity

  • Time: O(d)
  • Space: O(1)

12. Frequency of Digits

Concept

Digit frequency tells how many times each digit from 0 through 9 occurs. Example: 1223052 → 0:1, 1:1, 2:3, 3:1, 5:1.

Best Data Structure

Because there are exactly ten decimal digits, use int[] frequency = new int[10];. The array index represents the digit — frequency[5] stores the number of occurrences of digit 5.

Java Program

Java
public class DigitFrequency {
    public static void main(String[] args) {
        int number = 1223052;
        int temp = Math.abs(number);
        int[] frequency = new int[10];
        if (temp == 0) {
            frequency[0] = 1;
        } else {
            while (temp > 0) {
                int digit = temp % 10;
                frequency[digit]++;
                temp /= 10;
            }
        }
        for (int digit = 0; digit <= 9; digit++) {
            if (frequency[digit] > 0) {
                System.out.println(digit + " -> " + frequency[digit]);
            }
        }
    }
}

Output

Output
0 -> 1
1 -> 1
2 -> 3
3 -> 1
5 -> 1

Why an Array Is Better Than HashMap Here

The possible values are known in advance: 0 through 9. An array therefore gives:

  • Constant-time access
  • Very small fixed memory
  • Simpler logic
  • No boxing of integers
  • No hashing overhead

Complexity

  • Time: O(d)
  • Space: O(1)

Although an array is used, its size is always exactly 10, so auxiliary space remains constant.

Interview Variation

Common variations include:

  • Find the most frequent digit.
  • Find digits appearing exactly once.
  • Print repeated digits.
  • Find frequency of one specified digit.
  • Find the least frequent occurring digit.

13. Remove Last Digit

Concept

Integer division by 10 removes the final decimal digit. Example: 5837 / 10 = 583.

Java Program

Java
public class RemoveLastDigit {
    public static void main(String[] args) {
        int number = 5837;
        int result = number / 10;
        System.out.println("After removing last digit: " + result);
    }
}

Output

Output
After removing last digit: 583

More Examples

NumberAfter / 10
5837583
12012
454
70

Why It Works

Java integer division discards the fractional part. Mathematically 5837 / 10 = 583.7, but integer arithmetic stores 583 — the final digit disappears.

Negative Numbers

Java truncates integer division toward zero. Example: -5837 / 10 = -583.

Complexity

  • Time: O(1)
  • Space: O(1)

14. Extract Individual Digits

Concept

A number can be decomposed into individual decimal digits using % 10 and / 10. There are two common requirements:

  1. Extract digits from right to left.
  2. Extract digits in their original left-to-right order.

Approach 1: Extract Right to Left

Java
public class ExtractDigitsReverseOrder {
    public static void main(String[] args) {
        int number = 5837;
        int temp = Math.abs(number);
        while (temp > 0) {
            int digit = temp % 10;
            System.out.println(digit);
            temp /= 10;
        }
    }
}

Output:

Output
7
3
8
5

This happens because % 10 always accesses the last digit first.

Approach 2: Extract Left to Right

Find the highest power of 10 needed to isolate the first digit. For 5837: divisor = 1000, then 5837 / 1000 = 5. After processing each digit, reduce the divisor.

Java
public class ExtractDigitsOriginalOrder {
    public static void main(String[] args) {
        int number = 5837;
        int temp = Math.abs(number);
        int divisor = 1;
        while (temp / divisor >= 10) {
            divisor *= 10;
        }
        while (divisor > 0) {
            int digit = temp / divisor;
            System.out.println(digit);
            temp %= divisor;
            divisor /= 10;
        }
    }
}

Output:

Output
5
8
3
7

Dry Run

For 5837:

tempdivisordigit
583710005
8371008
37103
717

Which Approach Should You Use?

Use right-to-left extraction when digit order does not matter, such as:

  • Sum of digits
  • Product of digits
  • Maximum digit
  • Frequency counting

Use left-to-right extraction when processing order matters, such as:

  • Printing digits in original order
  • Sequential digit validation
  • Building formatted output

Complexity

  • Time: O(d)
  • Space: O(1)

15. Replace Digits in Number

Concept

Digit replacement changes every occurrence of one digit into another. Example: replace 2 with 9 in 12230421993049. This problem is more challenging because normal digit extraction works from right to left while the reconstructed number must preserve positional order.

Arithmetic Approach

Each extracted digit can be modified before being placed back at its correct decimal position.

Java Program

Java
public class ReplaceDigit {
    public static void main(String[] args) {
        int number = 1223042;
        int oldDigit = 2;
        int newDigit = 9;
        int temp = Math.abs(number);
        int result = 0;
        int place = 1;
        while (temp > 0) {
            int digit = temp % 10;
            if (digit == oldDigit) {
                digit = newDigit;
            }
            result += digit * place;
            place *= 10;
            temp /= 10;
        }
        if (number < 0) {
            result = -result;
        }
        System.out.println("Result: " + result);
    }
}

Output

Output
Result: 1993049

Dry Run

Digits are processed from right to left.

ExtractedReplacedPlaceContribution
2919
441040
001000
3310003000
291000090000
29100000900000
1110000001000000

Final result: 1993049

Why place Is Required

Without positional multiplication, extracted digits would lose their original place values — units multiply by 1, tens by 10, hundreds by 100, thousands by 1000.

Important Edge Case: Replacing with Zero

Suppose 1232, replace 2 with 0 → result 1030. The arithmetic approach handles internal and trailing zero replacements correctly as an integer. However, replacing a leading digit with zero changes the visible digit count: 123 with 1→0 is mathematically 023, but as an integer that is 23 — leading zeros cannot be stored in an integer representation.

Alternative String Approach

For formatting-oriented requirements, converting to a string can be simpler: String result = String.valueOf(number).replace('2', '9');. Use arithmetic when the purpose is to practice numeric logic. Use strings when textual representation is the actual requirement.

Complexity

  • Time: O(d)
  • Space: O(1) for the arithmetic version

Core Digit-Manipulation Patterns

Most problems in this chapter can be solved with a few reusable patterns.

Extract Last Digit

int digit = number % 10;

Remove Last Digit

number /= 10;

Process All Digits

Java
while (number > 0) {
    int digit = number % 10;
    // Process digit
    number /= 10;
}

Build a Number Digit by Digit

result = result * 10 + digit; — commonly used when reversing a number.

Preserve Original Place Value

result += digit * place; place *= 10; — useful when modifying digits while keeping their original positions.

Choosing the Correct Initial Value

Accumulator initialization changes according to the problem.

ProblemRecommended Initial Value
Sum of digits0
Product of digits1
Digit count0
Reverse number0
Largest digit0
Smallest digit9
Even digit count0
Odd digit count0
Frequency arrayall 0

Incorrect initialization is one of the most common causes of wrong answers in digit-based programs.

Handling Zero Correctly

Zero requires special attention because while (number > 0) does not execute when number == 0. Depending on the problem:

OperationResult for 0
Number of digits1
Sum of digits0
Product of digitsUsually 0
First digit0
Last digit0
Largest digit0
Smallest digit0
Even digit count1
Odd digit count0
Frequency of digit 01

The expected interpretation should follow the problem specification.

Handling Negative Numbers

For digit analysis, the sign usually does not participate in the calculation. A common pattern is int temp = Math.abs(number);. For example, -5832 contains the digits 5, 8, 3, 2, not five symbols including the minus sign.

When the result itself should preserve the sign, as with number reversal, restore it after processing. Example: -1234-4321.

Preserving the Original Number

Digit-processing loops normally destroy their working value:

Java
while (number > 0) {
    number /= 10;
}

After the loop, number == 0. If the original value is required later, create a temporary variable: int temp = number;, then perform all digit operations on temp. This is especially important in problems such as:

  • Palindrome checking
  • Armstrong number checking
  • Comparing original and reversed values
  • Printing the input after calculation

Arithmetic Approach vs String Approach

Digit problems can often be solved both numerically and through strings.

Arithmetic Approach

Example: int digit = number % 10;. Advantages:

  • Demonstrates number logic clearly
  • Uses constant auxiliary memory
  • Common in programming interviews
  • Builds understanding of division and modulo

Best for: digit sums, reverse number, digit counts, maximum/minimum digit, frequency problems.

String Approach

Example: String value = String.valueOf(number);. Advantages:

  • Easy left-to-right access
  • Convenient for replacement
  • Convenient when formatting matters

Best for: preserving leading zeros, character-oriented validation, formatting requirements.

For logic-development practice, arithmetic solutions should normally be understood first.

Important % and / Relationship

For a positive integer: digit = number % 10; number = number / 10;

Consider number = 5837. First iteration: digit = 5837 % 10 = 7, number = 5837 / 10 = 583. Second iteration: digit = 583 % 10 = 3, number = 583 / 10 = 58.

The number shrinks by approximately one decimal digit after each iteration. This is why most digit algorithms run in O(d) time.

Time Complexity of Digit Problems

If a number contains d digits, repeatedly dividing it by 10 requires approximately d iterations. Therefore Time Complexity = O(d). Since d ≈ log10(n) + 1, the same complexity can also be expressed as O(log10 n). In interview discussions, O(d) is often clearer because the algorithm directly processes each digit once.

Space Complexity

Most arithmetic digit problems use only a few variables: digit, temp, sum, count, result. Therefore Space Complexity = O(1). Digit frequency also remains O(1) because its array always contains exactly ten elements.

Common Mistakes Across Digit Problems

Using % 10 but Forgetting / 10

This creates an infinite loop because the number never changes. Incorrect: while (number > 0) { int digit = number % 10; }. Correct: also include number /= 10; inside the loop.

Destroying the Original Input

If the original number is needed later, operate on a copy: int temp = number;

Ignoring Zero

The standard positive-number loop does not process 0. Handle it separately when zero represents one actual digit.

Incorrect Product Initialization

Incorrect: int product = 0;. Correct: int product = 1;

Incorrect Minimum Initialization

Incorrect: int smallest = 0;. Correct: int smallest = 9; for ordinary positive decimal-digit scanning.

Reversing Without Considering Overflow

The expression reverse = reverse * 10 + digit; can exceed the range of an int. Use long or explicit overflow validation when the input range requires it.

Assuming Leading Zeros Are Stored

Integer 00123 is effectively represented numerically as 123. If leading zeros matter, use a String.

Reusable Digit Traversal Template

The following pattern can solve many interview problems by changing only the digit-processing logic.

Java
int temp = Math.abs(number);
while (temp > 0) {
    int digit = temp % 10;
    // Apply problem-specific logic here
    temp /= 10;
}

Examples of problem-specific logic:

Sum

sum += digit;

Product

product *= digit;

Count Even Digits

if (digit % 2 == 0) { evenCount++; }

Largest Digit

if (digit > largest) { largest = digit; }

Frequency

frequency[digit]++;

Understanding this reusable traversal is more valuable than memorizing separate programs.

Combined Digit Analysis in One Traversal

If several statistics are required, avoid scanning the number repeatedly. A single loop can calculate: number of digits, sum, product, largest digit, smallest digit, even digit count, odd digit count.

Java Program

Java
public class DigitAnalysis {
    public static void main(String[] args) {
        int number = 583264;
        int temp = Math.abs(number);
        int count = 0;
        int sum = 0;
        int product = temp == 0 ? 0 : 1;
        int largest = 0;
        int smallest = temp == 0 ? 0 : 9;
        int evenCount = 0;
        int oddCount = 0;
        if (temp == 0) {
            count = 1;
            evenCount = 1;
        } else {
            while (temp > 0) {
                int digit = temp % 10;
                count++;
                sum += digit;
                product *= digit;
                if (digit > largest) {
                    largest = digit;
                }
                if (digit < smallest) {
                    smallest = digit;
                }
                if (digit % 2 == 0) {
                    evenCount++;
                } else {
                    oddCount++;
                }
                temp /= 10;
            }
        }
        System.out.println("Digits: " + count);
        System.out.println("Sum: " + sum);
        System.out.println("Product: " + product);
        System.out.println("Largest: " + largest);
        System.out.println("Smallest: " + smallest);
        System.out.println("Even digits: " + evenCount);
        System.out.println("Odd digits: " + oddCount);
    }
}

Output

Output
Digits: 6
Sum: 28
Product: 5760
Largest: 8
Smallest: 2
Even digits: 4
Odd digits: 2

A single traversal is preferable when all statistics are required together because every digit is processed only once.

Interview-Focused Questions to Practice

  1. Count the digits of an integer without converting it to a string.
  2. Calculate the sum of all digits.
  3. Calculate the product of all digits.
  4. Reverse an integer.
  5. Reverse a negative integer while preserving its sign.
  6. Reverse a number while detecting integer overflow.
  7. Find the first digit without using strings.
  8. Find the last digit using modulo.
  9. Calculate the sum of the first and last digit.
  10. Find the maximum digit.
  11. Find the minimum digit.
  12. Count even digits.
  13. Count odd digits.
  14. Count occurrences of every decimal digit.
  15. Find the frequency of a specified digit.
  16. Find the most frequently occurring digit.
  17. Find all digits occurring exactly once.
  18. Remove the last digit.
  19. Print digits from right to left.
  20. Print digits from left to right without converting to a string.
  21. Replace every occurrence of one digit with another.
  22. Determine whether a number contains a specified digit.
  23. Count how many times a specified digit occurs.
  24. Check whether all digits are even.
  25. Check whether all digits are odd.
  26. Check whether digits are in increasing order.
  27. Find the second-largest digit.
  28. Find the difference between the largest and smallest digit.
  29. Swap the first and last digit.
  30. Calculate multiple digit statistics in one traversal.

Quick Reference

RequirementCore Logic
Extract last digitnumber % 10
Remove last digitnumber / 10
Count digitsincrement while dividing by 10
Sum digitssum += digit
Product digitsproduct *= digit
Reverse numberreverse = reverse * 10 + digit
First digitdivide until < 10
Last digitnumber % 10
Largest digitcompare using >
Smallest digitcompare using <
Even digitdigit % 2 == 0
Odd digitdigit % 2 != 0
Digit frequencyfrequency[digit]++
Remove final digitnumber /= 10
Replace digitcompare and reconstruct
Preserve inputprocess a temporary copy

Key Problem-Solving Rules

  • Use % 10 when you need the current last digit.
  • Use / 10 when you need to remove that digit.
  • Use a temporary variable when the original number must remain unchanged.
  • Handle 0 explicitly when the loop condition is number > 0.
  • Normalize negative numbers when only digits matter.
  • Initialize accumulators according to the operation.
  • Use an array of size 10 for decimal-digit frequencies.
  • Use arithmetic approaches for interview-focused logic practice.
  • Use strings when preserving textual formatting such as leading zeros is part of the requirement.
  • Combine related calculations into one traversal when possible.

Question Hint