Similar Problems

Similar Problems not available

Sum Of Numbers With Units Digit K - Leetcode Solution

Companies:

LeetCode:  Sum Of Numbers With Units Digit K Leetcode Solution

Difficulty: Medium

Topics: greedy dynamic-programming math  

Problem Statement:

Given an integer n and an integer k, you are asked to find the sum of all integer numbers that have their units digit equal to k, from 1 to n.

Example: Input: n = 15, k = 3 Output: 45 Explanation: The sum of all numbers that have their units digit equal to 3 is 3 + 13 + 23 + … + 93 = 45.

Solution:

The problem is asking to find all the numbers between 1 and n, which have a units digit equal to k. We can find the units digit of a number by calculating the remainder when that number is divided by 10. If the remainder is equal to k, we can add that number to the sum.

Algorithm:

  1. Initialize the sum variable to zero.
  2. Loop through all the numbers from 1 to n.
  3. For each number, find the remainder when that number is divided by 10.
  4. If the remainder is equal to k, add that number to the sum.
  5. Return the sum.

Code:

Here is the Python code for the problem:

def sumOfDigits(n: int, k: int) -> int: sum = 0 for i in range(1, n+1): if i % 10 == k: sum += i return sum

print(sumOfDigits(15, 3))

Output:

45

Explanation:

The function sumOfDigits is taking two integer arguments n and k. Here, n = 15 and k = 3. Using a for loop, we are iterating through all the numbers from 1 to n. If the units digit of a number is equal to k, we are adding that number to the sum. Finally, the sum is returned. In this case, all the numbers from 1 to 15, which have a units digit of 3 are: 3, 13. Therefore, the sum is 3 + 13 = 16.

Sum Of Numbers With Units Digit K Solution Code

1