Skip to content

3270. Find the Key of the Numbers 👍

  • Time: $O(1)$
  • Space: $O(1)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class Solution {
 public:
  int generateKey(int num1, int num2, int num3) {
    const string s1 = zfill(num1, 4);
    const string s2 = zfill(num2, 4);
    const string s3 = zfill(num3, 4);
    string ans;

    for (int i = 0; i < 4; ++i)
      ans += min({s1[i], s2[i], s3[i]});

    return stoi(ans);
  }

 private:
  string zfill(int num, int width) {
    ostringstream oss;
    oss.width(width);
    oss.fill('0');
    oss << num;
    return oss.str();
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
class Solution {
  public int generateKey(int num1, int num2, int num3) {
    final String s1 = String.format("%04d", num1);
    final String s2 = String.format("%04d", num2);
    final String s3 = String.format("%04d", num3);
    StringBuilder sb = new StringBuilder();

    for (int i = 0; i < 4; ++i)
      sb.append((char) Math.min(Math.min(s1.charAt(i), s2.charAt(i)), s3.charAt(i)));

    return Integer.parseInt(sb.toString());
  }
}
1
2
3
4
5
6
class Solution:
  def generateKey(self, num1: int, num2: int, num3: int) -> int:
    return int(''.join(min(a, b, c)
                       for a, b, c in zip(str(num1).zfill(4),
                                          str(num2).zfill(4),
                                          str(num3).zfill(4))))