如果我有String x =" 2016"如何将其转换为int类型的6210?
我正在尝试
String x = "2016"
int v = 0;
for (int k = 0; k < x.length(); k++) {
if (v < x.charAt(k) - '0') {
v = x.charAt(k) - '0';
}
}
v *= 1000;
但我不知道下一步该做什么
答案 0 :(得分:0)
char[] stringVals = x.toCharArray();
int[] results = new int[stringVals.length];
for (int i = 0; i < stringVals.length; i++) {
try {
results[i] = Integer.parseInt(stringVals[i]);
} catch (NumberFormatException nfe) {
//NOTE: write something here if you need to recover from formatting errors
};
}
Arrays.sort(results);
String sortedResult = Arrays.toString(results);
答案 1 :(得分:0)
尝试查看Integer.parseInt
但你不能使用chars(作为他们答案中提到的前一张海报)因为char与Integer.parseInt不兼容,只有字符串。
尝试将String解析为如下数组:
String[] numbers = x.split("");
潜在的解决方案:
String x = "2016";
String[] numbers = x.split("");
Integer[] nums = new Integer[numbers.length];
for (int k = 0; k < numbers.length; k++) {
nums[k] = Integer.parseInt(numbers[k]);
}
Arrays.sort(nums, Collections.reverseOrder());
StringBuilder strNum = new StringBuilder();
for (int num : nums){
strNum.append(num);
}
int finalInt = Integer.parseInt(strNum.toString());
System.out.println(finalInt);
答案 2 :(得分:0)
使用java-8
String reversed = Arrays.stream(x.split(""))
.sorted(String.CASE_INSENSITIVE_ORDER.reversed())
.collect(Collectors.joining());
int v = Integer.parseInt(reversed);