comments | difficulty | edit_url | rating | source | tags | |
---|---|---|---|---|---|---|
true |
Easy |
1205 |
Biweekly Contest 138 Q1 |
|
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 thekey
is generated by taking the smallest digit among theith
digits 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
1st
digit of thekey
ismin(0, 0, 1)
. - The
2nd
digit of thekey
ismin(0, 0, 0)
. - The
3rd
digit of thekey
ismin(0, 1, 0)
. - The
4th
digit of thekey
ismin(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
We can directly simulate this process by defining a variable
Starting from the units place, for each digit place, we calculate the current digit of
Finally, return the answer.
The time complexity is
class Solution:
def generateKey(self, num1: int, num2: int, num3: int) -> int:
ans, k = 0, 1
for _ in range(4):
x = min(num1 // k % 10, num2 // k % 10, num3 // k % 10)
ans += x * k
k *= 10
return ans
class Solution {
public int generateKey(int num1, int num2, int num3) {
int ans = 0, k = 1;
for (int i = 0; i < 4; ++i) {
int x = Math.min(Math.min(num1 / k % 10, num2 / k % 10), num3 / k % 10);
ans += x * k;
k *= 10;
}
return ans;
}
}
class Solution {
public:
int generateKey(int num1, int num2, int num3) {
int ans = 0, k = 1;
for (int i = 0; i < 4; ++i) {
int x = min({num1 / k % 10, num2 / k % 10, num3 / k % 10});
ans += x * k;
k *= 10;
}
return ans;
}
};
func generateKey(num1 int, num2 int, num3 int) (ans int) {
k := 1
for i := 0; i < 4; i++ {
x := min(min(num1/k%10, num2/k%10), num3/k%10)
ans += x * k
k *= 10
}
return
}
function generateKey(num1: number, num2: number, num3: number): number {
let [ans, k] = [0, 1];
for (let i = 0; i < 4; ++i) {
const x = Math.min(((num1 / k) | 0) % 10, ((num2 / k) | 0) % 10, ((num3 / k) | 0) % 10);
ans += x * k;
k *= 10;
}
return ans;
}