Similar Problems

Similar Problems not available

Calculate Digit Sum Of A String - Leetcode Solution

Companies:

LeetCode:  Calculate Digit Sum Of A String Leetcode Solution

Difficulty: Easy

Topics: string simulation  

Problem statement:

Given a string str containing alphanumeric characters, we need to calculate the sum of all digits present in the string.

Example:

Input: str = "1abc23def4" Output: 10 Explanation: The digits present in the string are 1, 2, 3, and 4. The sum of these digits is 10.

Solution:

We can solve this problem by iterating over each character of the string and checking if it is a digit or not.

If it is a digit, we can add it to a variable sum which will store the sum of digits.

Here is the code to solve the problem:

public int calculateDigitSum(String str) {
    int sum = 0;

    // Iterate over each character of the string
    for (int i = 0; i < str.length(); i++) {
        char ch = str.charAt(i);

        // If the character is a digit, add it to the sum
        if (Character.isDigit(ch)) {
            sum += Character.getNumericValue(ch);
        }
    }

    // Return the sum of digits present in the string
    return sum;
}

Explanation:

We start by initializing a variable sum to 0.

Then we iterate over each character of the string using a for loop and get the current character using the charAt() method.

If the current character is a digit, we add it to the sum by using the isDigit() method to check if the character is a digit and then using the getNumericValue() method to convert the character to its corresponding integer value.

Finally, we return the sum of digits present in the string.

This solution has a time complexity of O(n), where n is the length of the string. The space complexity is O(1), as we only need a single variable to store the sum.

Calculate Digit Sum Of A String Solution Code

1