EASY
Find the Key of the Numbers
You are given three positive integers num1, num2, and num3.
The key of num1, num2, and num3 is defined as a four-digit number such that:
- Initially, if any number has less than four digits, it is padded with leading zeros.
- The ith digit (1 ≤ i ≤ 4) of the key is generated by taking the smallest digit among the ith digits of
num1,num2, andnum3. - Return the key of the three numbers without leading zeros (if any).
Example
Input:
num1 = 2435
num2 = 1734
num3 = 5678
1434
Explanation: - Pad all numbers to 4 digits: 2435, 1734, 5678 - 1st digit: min(2,1,5) = 1 - 2nd digit: min(4,7,6) = 4 - 3rd digit: min(3,3,7) = 3 - 4th digit: min(5,4,8) = 4 - The key is 1434 (no leading zeros to remove)
Constraints
- 1 ≤ num1, num2, num3 ≤ 9999
Solution
- Time Complexity: O(1)
- Space Complexity: O(1)
C++
class Solution {
public:
int generateKey(int num1, int num2, int num3) {
int ans = 0;
int m = 1;
while(num1 || num2 || num3) {
int val = min({num1%10, num2%10, num3%10});
ans += val*m;
num1 /= 10;
num2 /= 10;
num3 /= 10;
m *= 10;
}
return ans;
}
};