Advertisement

Count Integers With Even Digit Sum - LeetCode 2180 Solution

Count Integers With Even Digit Sum - Complete Solution Guide

Count Integers With Even Digit Sum is LeetCode problem 2180, a Easy level challenge. This complete guide provides step-by-step explanations, multiple solution approaches, and optimized code in python3, java, cpp, c.

Problem Statement

Given a positive integer num , return the number of positive integers less than or equal to num whose digit sums are even . The digit sum of a positive integer is the sum of all its digits. Example 1: Input: num = 4 Output: 2 Explanation: The only integers less than or equal to 4 whose digit sums are even are 2 and 4. Example 2: Input: num = 30 Output: 14 Explanation: The 14 integers less than or equal to 30 whose digit sums are even are 2, 4, 6, 8, 11, 13, 15, 17, 19, 20, 22, 24, 26, and 28. Co

Detailed Explanation

The problem asks you to count the number of positive integers from 1 up to a given integer `num` (inclusive) where the sum of their digits is even. For example, if `num` is 4, the integers are 1, 2, 3, 4. The digit sums are 1, 2, 3, 4 respectively. Only 2 and 4 have even digit sums, so the answer is 2. The input `num` is guaranteed to be between 1 and 1000.

Solution Approach

The provided solutions use a brute-force approach. They iterate through each number from 1 to `num`. For each number, they calculate the sum of its digits. If this sum is even, a counter is incremented. Finally, the counter (representing the number of integers with even digit sums) is returned.

Step-by-Step Algorithm

  1. Step 1: Initialize a counter `count` to 0.
  2. Step 2: Iterate through numbers from 1 to `num` (inclusive).
  3. Step 3: For each number, calculate the sum of its digits. This can be done by converting the number to a string, iterating through its digits, converting them back to integers and summing them, or by repeatedly using the modulo operator (%) and integer division (/).
  4. Step 4: Check if the sum of digits is even using the modulo operator (`%`).
  5. Step 5: If the sum is even, increment the `count`.
  6. Step 6: After iterating through all numbers, return the final value of `count`.

Key Insights

  • Insight 1: We need to iterate through each number from 1 to `num` and calculate the sum of its digits.
  • Insight 2: A simple iterative approach is sufficient due to the constraint that `num` is at most 1000.
  • Insight 3: No significant optimizations are needed for this problem given the constraints, though a mathematical approach could improve performance for much larger inputs.

Complexity Analysis

Time Complexity: O(n*log(n))

Space Complexity: O(1)

Topics

This problem involves: Math, Simulation.

Companies

Asked at: MindTree.