题目:给出一个由‘0’-‘9’数字构成的字符串,重新排列字符串的顺序,并将字符串拆分成两个非负整数a、b,可包含前缀0,求a+b的最大值。数据长度:2<=|s|<=1000
实例:s = '123',cal(s) = '33'
s='999999999999991',cal(s) = '100000000000000'
分析:设计字符串、字符、整数的互相转换,以及整型上溢的问题。
</pre><pre name="code" class="java">public class Solution(){
public static void main(String[] args){
String numS = "9999991";
System.out.println(cal(numS));
}
public static String cal(String s) {
if (s == null || s.length() < 2)
return "Illeagal input!";
String result = "";
int len = s.length();
char[] ch = new char[len];
ch = s.toCharArray();
Arrays.sort(ch);
ArrayList<Integer> number = new ArrayList<Integer>();
for (int i = 0; i < len; i++) {
number.add(ch[i] - 48);
}
int carry = 0;
if (number.get(0) + number.get(1) >= 10) {
for (int i = 0; i < len; i++) {
if (i == len - 1) {
number.add(carry);
} else {
int mm = number.get(i) + number.get(i + 1) + carry;
carry = mm / 10;
int temp = mm % 10;
number.set(i + 1, temp);
}
}
} else {
number.set(1, number.get(0) + number.get(1));
}
StringBuilder sb = new StringBuilder();
for (int i = number.size() - 1; i > 0; i--) {
sb.append(number.get(i));
}
result = sb.toString();
if (result.charAt(0) == '0') {
result = "0";
}
return result;
}
}