Sum of Numbers With Units Digit K – Java Solution

Explore Solutions in Other Languages

Problem Description

So, you’ve found yourself in a situation where you need to figure out how many numbers you can add together to reach a specific total, but there’s a catch: each of those numbers must end with the digit k. Sounds like a fun party game, right? Imagine you’re at a birthday party, and the only gifts you can give are those that have a specific wrapping paper (the units digit). You can’t just throw any old gift at the birthday kid; it has to be wrapped just right!

In this problem, you’re given two integers, num and k. Your task is to find the minimum number of integers that can be summed up to equal num, where each integer ends with the digit k. If it’s impossible, you should return -1.

Code Solution

Here’s the Java solution that will help you solve this delightful conundrum:


class Solution {
  public int minimumNumbers(int num, int k) {
    if (num == 0)
      return 0;

    for (int i = 1; i <= 10 && i * k <= num; ++i)
      if (i * k % 10 == num % 10)
        return i;

    return -1;
  }
}

Approach

The approach taken in this solution is quite straightforward. The code checks if num is zero, in which case it returns 0 because you don’t need any numbers to sum up to zero. Then, it iterates from 1 to 10, checking if the product of the current index i and k can yield a number that matches the last digit of num. If it finds such a number, it returns i, which represents the minimum count of numbers needed. If no such number is found, it returns -1.

Time and Space Complexity

Time Complexity: O(1) - The loop runs a maximum of 10 times, which is constant time.

Space Complexity: O(1) - No additional space is used that scales with input size.

Real-World Example

Imagine you’re at a candy store, and you want to buy candies that cost a specific amount, say num dollars. However, the store has a quirky rule: you can only buy candies that cost k dollars each. You need to figure out the minimum number of candies you can buy to reach exactly num dollars. If you can’t reach that amount with the candies available, you might as well just leave the store empty-handed.

Similar Problems

If you enjoyed this problem, you might also like these: