3270. Find the Key of the Numbers
- You are given three positive integers
num1
,num2
, andnum3
. - The
key
ofnum1
,num2
, andnum3
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 the key is min(0, 0, 1).
The 2nd digit of the key is min(0, 0, 0).
The 3rd digit of the key is min(0, 1, 0).
The 4th digit of the key is min(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
Method 1
【O(1) time | O(1) space】
package Leetcode.Math;
/**
* @author zhengxingxing
* @date 2025/01/11
*/
public class FindTheKeyOfTheNumbers {
public static int findKey(int num1, int num2, int num3) {
// Convert numbers to 4-digit strings with leading zeros
String s1 = String.format("%04d", num1);
String s2 = String.format("%04d", num2);
String s3 = String.format("%04d", num3);
StringBuilder key = new StringBuilder();
// Iterate through each digit and find the minimum value
for (int i = 0; i < 4; i++) {
int digit = Math.min(Math.min(
s1.charAt(i) - '0',
s2.charAt(i) - '0'),
s3.charAt(i) - '0'
);
key.append(digit);
}
// Convert to integer and return
return Integer.parseInt(key.toString());
}
public static void main(String[] args) {
// Test case 1
System.out.println("Test case 1:");
int num1 = 1, num2 = 10, num3 = 1000;
System.out.println("Input: num1 = " + num1 + ", num2 = " + num2 + ", num3 = " + num3);
System.out.println("Output: " + findKey(num1, num2, num3));
// Test case 2
System.out.println("\nTest case 2:");
num1 = 987; num2 = 879; num3 = 798;
System.out.println("Input: num1 = " + num1 + ", num2 = " + num2 + ", num3 = " + num3);
System.out.println("Output: " + findKey(num1, num2, num3));
// Test case 3
System.out.println("\nTest case 3:");
num1 = 1; num2 = 2; num3 = 3;
System.out.println("Input: num1 = " + num1 + ", num2 = " + num2 + ", num3 = " + num3);
System.out.println("Output: " + findKey(num1, num2, num3));
}
}
Enjoy Reading This Article?
Here are some more articles you might like to read next: