Sum Of Digits Of A Number In Java Leetcode Solution
This article will guide you through various methods to calculate the sum of digits of a number in Java. You will learn how to approach this common programming problem using different techniques.
Problem Statement
The task is to find the sum of the individual digits of a given non-negative integer. For example, if the input number is 123, the sum of its digits would be 1 + 2 + 3 = 6. This is a fundamental problem often encountered in coding challenges and can be solved in multiple ways.
Example
If the input number is 456, the expected output is 15.
Background & Knowledge Prerequisites
To understand this article, you should have a basic understanding of:
- Java primitive data types (especially
int). - Arithmetic operators (
%for modulo,/for division). - Control flow statements (
whileloop). - String manipulation (for string-based approaches).
Use Cases or Case Studies
Calculating the sum of digits can be useful in various scenarios:
- Checksum Validation: Some algorithms use the sum of digits (or a variation like the Luhn algorithm) for basic data validation.
- Digital Root: Repeatedly summing digits until a single digit remains is used in numerology and some mathematical puzzles.
- Number Theory Problems: Many number theory problems involve analyzing the properties of digits within a number.
- Educational Exercises: It's a common beginner-friendly problem to practice loops and arithmetic operations.
- Hashing Functions: Simple hashing functions might incorporate digit sums.
Solution Approaches
Here are a few common approaches to solve this problem.
Approach 1: Using Modulo and Division (Iterative)
This is the most common and efficient approach. It repeatedly extracts the last digit using the modulo operator and then removes it using integer division.
- One-line summary: Extracts digits one by one using
% 10and/ 10in a loop.
// Sum of Digits using Modulo and Division
import java.util.Scanner;
// Main class containing the entry point of the program
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// Step 1: Get input number from the user
System.out.print("Enter a non-negative integer: ");
int number = scanner.nextInt();
// Step 2: Initialize sum
int sum = 0;
// Step 3: Loop until the number becomes 0
int tempNumber = number; // Use a temporary variable to preserve original number
while (tempNumber != 0) {
// Get the last digit
int digit = tempNumber % 10;
// Add the digit to sum
sum += digit;
// Remove the last digit
tempNumber /= 10;
}
// Step 4: Print the result
System.out.println("The sum of digits of " + number + " is: " + sum);
scanner.close();
}
}
Sample Output:
Enter a non-negative integer: 789
The sum of digits of 789 is: 24
Stepwise Explanation:
- Initialize
sumto 0: This variable will store the accumulated sum of digits. - Use a
whileloop: The loop continues as long astempNumberis not 0. - Extract last digit:
tempNumber % 10gives the remainder whentempNumberis divided by 10, which is its last digit. - Add to
sum: The extracteddigitis added to thesum. - Remove last digit:
tempNumber /= 10performs integer division, effectively removing the last digit fromtempNumber. - Repeat: The loop continues with the modified
tempNumberuntil all digits have been processed.
Approach 2: Using String Conversion
This approach converts the number to a string, iterates through its characters, converts each character back to a digit, and sums them up.
- One-line summary: Converts the number to a string, then iterates through each character, converting it back to an integer.
// Sum of Digits using String Conversion
import java.util.Scanner;
// Main class containing the entry point of the program
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// Step 1: Get input number from the user
System.out.print("Enter a non-negative integer: ");
int number = scanner.nextInt();
// Step 2: Convert the integer to a string
String numStr = String.valueOf(number);
// Step 3: Initialize sum
int sum = 0;
// Step 4: Iterate through each character of the string
for (int i = 0; i < numStr.length(); i++) {
// Get the character at current index
char digitChar = numStr.charAt(i);
// Convert character to integer and add to sum
sum += Character.getNumericValue(digitChar);
}
// Step 5: Print the result
System.out.println("The sum of digits of " + number + " is: " + sum);
scanner.close();
}
}
Sample Output:
Enter a non-negative integer: 1024
The sum of digits of 1024 is: 7
Stepwise Explanation:
- Convert to String:
String.valueOf(number)converts the integernumberinto its string representation. - Initialize
sumto 0: This variable will store the accumulated sum. - Iterate through characters: A
forloop iterates from the first character to the last character of thenumStr. - Get character:
numStr.charAt(i)retrieves the character at the current indexi. - Convert char to int:
Character.getNumericValue(digitChar)converts the character ('0' through '9') into its corresponding integer value (0 through 9). - Add to
sum: The converted digit is added to thesum.
Approach 3: Using Recursion
Recursion offers an elegant way to solve this problem by breaking it down into smaller, similar subproblems.
- One-line summary: Defines a recursive function that sums the last digit with the sum of digits of the remaining number