1
給定一個字符串,其中包含許多正整數。如何按照他們的數字總和來排列它們。意味着最小的數字總和將出現在左側,最大的數字總和將出現在右側。字符串中的整數由字符數組合排列
例如:
我有一個字符串= 「
2000 10003 1234000 44444444 9999 11 11 22 123
」。因爲:11具有數位總和=
1+1 = 2
;- 2000具有數字總和=
2 + 0 + 0 + 0 = 2
; - 10003有數字總和=
1 + 0 + 0 + 0 + 3 = 4...
那麼,如何才能做到這一點?
這裏是我的代碼:
import java.util.Map;
import java.util.TreeMap;
//String s = "2000 10003 1234000 44444444 9999 11 11 22 123";
//return "11 11 2000 10003 22 123 1234000 44444444 9999",
public class WeightSort {
public static String orderWeight(String string) {
Map<Integer, String> chunks = new TreeMap<>();
for (String chunk : string.split (" ")) {
int sum = 0;
for (int i = 0; i < chunk.length(); i++) {
sum += Integer.parseInt ("" + chunk.charAt (i));
}
chunks.put (sum, chunk);
}
String s = chunks.values().toString();
String result = s.substring(1).replaceAll(", ", " ").replaceAll("]", "");
return result;
}
public static void main(String[] args){
String s = "2000 10003 1234000 44444444 9999 11 11 22 123";
System.out.println(WeightSort.orderWeight(s));
}
}
但它只返回:"11 22 123 1234000 44444444 9999"
這是行不通的,它返回「,2000年11月11日10003 22 123 1234000 44444444 9999 「 – Khuong
@ khuong291這是正確的結果。它保持項目具有相同的數字和,與原始列表中的順序相同(這種屬性被稱爲* stable *)。 – dasblinkenlight
是的,你說得對,但我想要其他的東西。因爲2000年和11年,他們都有數字= 2的總和,但是字母'1'首先以'2'出現,所以「11」首先以「2000」出現。 – Khuong