3270. Find the Key of the Numbers
SourceBiweekly Contest 138 Q1DifficultyEasyRating1205
Description
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
ithdigit (1 <= i <= 4) of thekeyis generated by taking the smallest digit among theithdigits ofnum1,num2, andnum3.
Return the key of the three numbers without leading zeros (if any).
Example 1:
Input: num1 = 1, num2 = 10, num3 = 1000
Output: 0
Explanation:
On padding, num1 becomes "0001", num2 becomes "0010", and num3 remains "1000".
- The
1stdigit of thekeyismin(0, 0, 1). - The
2nddigit of thekeyismin(0, 0, 0). - The
3rddigit of thekeyismin(0, 1, 0). - The
4thdigit of thekeyismin(1, 0, 0).
Hence, the key is "0000", i.e. 0.
Example 2:
Input: num1 = 987, num2 = 879, num3 = 798
Output: 777
Example 3:
Input: num1 = 1, num2 = 2, num3 = 3
Output: 1
Constraints:
1 <= num1, num2, num3 <= 9999
Solutions
Solution 1: Simulation
Thinking
Digit \(d\) of the key is the minimum of the three numbers' \(d\)-th digits, missing high digits treated as zero. There are four digits, so take minima and add with place weights.
For \(k=1,10,100,1000\) add \(\min_i (x_i//k)\% 10\) times \(k\). No string conversion is required.
We can directly simulate this process by defining a variable \(\textit{ans}\) to store the answer and a variable \(\textit{k}\) to represent the current digit place, where \(\textit{k} = 1\) represents the units place, \(\textit{k} = 10\) represents the tens place, and so on.
Starting from the units place, for each digit place, we calculate the current digit of \(\textit{num1}\), \(\textit{num2}\), and \(\textit{num3}\), take the minimum of the three, and then add this minimum value multiplied by \(\textit{k}\) to the answer. Then, multiply \(\textit{k}\) by 10 and continue to the next digit place.
Finally, return the answer.
The time complexity is \(O(1)\), and the space complexity is \(O(1)\).
1 2 3 4 5 6 7 8 | |
1 2 3 4 5 6 7 8 9 10 11 | |
1 2 3 4 5 6 7 8 9 10 11 12 | |
1 2 3 4 5 6 7 8 9 | |
1 2 3 4 5 6 7 8 9 | |