Similar Problems

Similar Problems not available

Minimum Addition To Make Integer Beautiful - Leetcode Solution

Companies:

LeetCode:  Minimum Addition To Make Integer Beautiful Leetcode Solution

Difficulty: Medium

Topics: greedy math  

Problem Statement: Given a positive integer N, you need to find the smallest positive integer M (M >= N) such that the sum of its digits in base 10 equals the sum of its digits in base 12.

Example: Input: 19 Output: 21 Explanation: The sum of digits in base 10 is 1+9=10 and in base 12 is 1+7=8. So, 21 is the next integer which satisfies the condition.

Approach: We can solve the problem by following these steps:

  1. Calculate the sum of digits of N in base 10 and store it in a variable say sum_base10.
  2. Calculate the sum of digits of N in base 12 and store it in a variable say sum_base12.
  3. Keep incrementing the integer M until its sum of digits in base 10 equals to sum_base10 and sum of digits in base 12 equals to sum_base12.
  4. Return the value of M.

Let's implement the above approach in code.

Code:

int getDigitsSum(int n, int base){ //Function to calculate the sum of digits of a given number in a specified base. int sum = 0; while(n > 0){ sum += n % base; n /= base; } return sum; }

int minimumAdditionToMakeIntegerBeautiful(int n){ int sum_base10 = getDigitsSum(n, 10); int sum_base12 = getDigitsSum(n, 12);

int m = n + 1; //incrementing the number until it satisfies the condition.
while(getDigitsSum(m, 10) != sum_base10 || getDigitsSum(m, 12) != sum_base12){
    m++;
}
return m;

}

Time Complexity: The time complexity of the above solution is O(k*log10(n)) where k is the maximum number of digits in the solution. In the worst case, k can be log10(n) because the number of digits in the solution cannot be more than log10(n).

Space Complexity: The space complexity of the above solution is O(1) because we are not using any extra space.

Minimum Addition To Make Integer Beautiful Solution Code

1