DEV Community

Cover image for Solving the "Largest Digit Sum" Problem on LeetCode
Bollam Shiva Shankara
Bollam Shiva Shankara

Posted on • Edited on

Solving the "Largest Digit Sum" Problem on LeetCode

Image 1

The Challenge

Question:

Given a set of numbers, your task is to find the largest digit in each number and calculate the sum of these largest digits.

The Code

Let's break down the code used to solve this challenge step by step. We'll be using Java for our implementation.

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        System.out.print("Enter the number of numbers: ");
        int numberOfNumbers = scanner.nextInt();

        int sumOfLargestDigits = 0;

        for (int i = 0; i < numberOfNumbers; i++) {
            System.out.print("Enter a number: ");
            int num = scanner.nextInt();
            int largestDigit = findLargestDigit(num);
            sumOfLargestDigits += largestDigit;
        }

        scanner.close();

        System.out.println("Sum of largest digits: " + sumOfLargestDigits);
    }

    public static int findLargestDigit(int number) {
        int largestDigit = 0;
        while (number > 0) {
            int digit = number % 10;
            largestDigit = Math.max(largestDigit, digit);
            number /= 10;
        }
        return largestDigit;
    }
}
Enter fullscreen mode Exit fullscreen mode

Explanation

1. Taking User Input: The program starts by using the Scanner class to take input from the user. First, it asks the user to specify the number of numbers they want to input.

2. Initializing Variables: The program initializes two important variables: sumOfLargestDigits (to store the sum of the largest digits) and largestDigit (to temporarily store the largest digit found in each number).

3. Loop Through Numbers: Using a for loop, the program iterates through each number as specified by the user. Inside the loop, it asks the user to enter a number and stores it in the variable num.

4. Finding the Largest Digit: The findLargestDigit function is called to find the largest digit in the entered number num. This function iterates through the digits of the number and keeps track of the largest digit found.

5. Summing the Largest Digits: The largest digit found in each number is added to the sumOfLargestDigits variable.

6. Closing the Scanner: After processing all the numbers, the program closes the Scanner to release system resources.

7. Displaying the Result: Finally, the program displays the sum of the largest digits.

Happy coding,
shiva

Top comments (0)