3270. Find the Key of the Numbers
Problem
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
iᵗʰdigit (1 <= i <= 4) of thekeyis generated by taking the smallest digit among theiᵗʰdigits ofnum1,num2, andnum3.
Return the key of the three numbers without leading zeros (if any).
https://leetcode.cn/problems/find-the-key-of-the-numbers/
Example 1:
Input:
num1 = 1, num2 = 10, num3 = 1000
Output:0
Explanation:
On padding,num1becomes"0001",num2becomes"0010", andnum3remains"1000".
- The 1ˢᵗ digit of the
keyismin(0, 0, 1).- The 2ⁿᵈ digit of the
keyismin(0, 0, 0).- The 3ʳᵈ digit of the
keyismin(0, 1, 0).- The 4ᵗʰ digit of the
keyismin(1, 0, 0).Hence, the
keyis"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
Test Cases
class Solution:
def generateKey(self, num1: int, num2: int, num3: int) -> int:solution_test.py下载完整源码
import pytest
from solution import Solution
@pytest.mark.parametrize('num1, num2, num3, expected', [
(1, 10, 1000, 0),
(987, 879, 798, 777),
(1, 2, 3, 1),
])
@pytest.mark.parametrize('sol', [Solution()])
def test_solution(sol, num1, num2, num3, expected):
assert sol.generateKey(num1, num2, num3) == expected
Thoughts
Code
solution.py下载完整源码
class Solution:
def generateKey(self, num1: int, num2: int, num3: int) -> int:
nums = [num1, num2, num3]
key = 0
base = 1
for _ in range(4):
d = 9
for j in range(3):
nums[j], r = divmod(nums[j], 10)
if r < d: d = r
key += d * base
base *= 10
return key
评论需要 JavaScript。