LeetCode(Sorting)2160. Minimum Sum of Four Digit Number After Splitting Digits

秒速五厘米 2023-09-23 23:54 219阅读 0赞

1.问题

You are given a positive integer num consisting of exactly four digits. Split num into two new integers new1 and new2 by using the digits found in num. Leading zeros are allowed in new1 and new2, and all the digits found in num must be used.

For example, given num = 2932, you have the following digits: two 2’s, one 9 and one 3. Some of the possible pairs [new1, new2] are [22, 93], [23, 92], [223, 9] and [2, 329].
Return the minimum possible sum of new1 and new2.

Example 1:

Input: num = 2932
Output: 52
Explanation: Some possible pairs [new1, new2] are [29, 23], [223, 9], etc.
The minimum sum can be obtained by the pair [29, 23]: 29 + 23 = 52.

Example 2:

Input: num = 4009
Output: 13
Explanation: Some possible pairs [new1, new2] are [0, 49], [490, 0], etc.
The minimum sum can be obtained by the pair [4, 9]: 4 + 9 = 13.

Constraints:

  • 1000 <= num <= 9999

2. 解题思路

方法1:

把个十百千位的数字放入到数组中,进行排序,按照规则计算

方法2:

1.int转为String,再转为char数组
2.对char数组排序
3.将数组中的char两两成对后转为int型相加,并返回结果

3. 代码

代码1:

  1. class Solution {
  2. public int minimumSum(int num) {
  3. int[] n1= new int[4];
  4. for(int i =3;i>=0;i--){
  5. //把个十百千位的数字放入到数组中,进行排序,按照n1[1]*10+n1[3]的规则计算
  6. n1[i]=num/(int) Math.pow(10,i);
  7. num=num%(int) Math.pow(10,i);
  8. }
  9. Arrays.sort(n1);
  10. int result =(n1[0]*10+n1[2])+(n1[1]*10+n1[3]);
  11. return result;
  12. }
  13. }

和以上解题思路基本相同

  1. class Solution
  2. {
  3. public int minimumSum(int num)
  4. {
  5. int[] dig = new int[4]; // For each digit
  6. int cur = 0;
  7. while(num > 0) // Getting each digit
  8. {
  9. dig[cur++] = num % 10;
  10. num /= 10;
  11. }
  12. Arrays.sort(dig); // Ascending order
  13. int num1 = dig[0] * 10 + dig[2]; // 1st and 3rd digit
  14. int num2 = dig[1] * 10 + dig[3]; // 2nd and 4th digit
  15. return num1 + num2;
  16. }
  17. }
  18. public int minimumSum(int num) {
  19. int []a={
  20. num%10,(num/10)%10,(num/100)%10 , (num/1000)%10};
  21. Arrays.sort(a);
  22. return a[0]*10+a[3]+a[1]*10+a[2];
  23. }

代码2:

  1. class Solution {
  2. public int minimumSum(int num) {
  3. char[] ch=(num+"").toCharArray();//1.int转为String,再转为char数组
  4. Arrays.sort(ch);//2.对char数组排序
  5. int n=Integer.parseInt(""+ch[0]+ch[2]);//3.将数组中的char两两成对后转为int型相加,并返回结果
  6. int m=Integer.parseInt(""+ch[1]+ch[3]);
  7. return n+m;
  8. }
  9. }

发表评论

表情:
评论列表 (有 0 条评论,219人围观)

还没有评论,来说两句吧...

相关阅读