控制臺(tái)數(shù)據(jù)需要累加的數(shù)字串個(gè)數(shù)及數(shù)字串伐债,計(jì)算成累加和并輸出
5
1111111111111111111111111111
23413412323452345
2222222222222222222
6666666666666666666666
44444444444444444444444444
方法一:使用java api
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String result="";
int n = sc.nextInt();
for(int i = 0; i < n; i++){
String input=sc.next();
if(result.equals("")) {
result=input;
}
else {
BigInteger b1=new BigInteger(result);
BigInteger b2=new BigInteger(input);
result=b1.add(b2).toString();
}
}
System.out.println(result);
}
方法二:
- 1嫁艇、讀取輸入數(shù)據(jù)
- 2攀芯、循環(huán)相加兩數(shù),獲取輸入最長(zhǎng)數(shù)據(jù)的長(zhǎng)度附鸽,不足最長(zhǎng)長(zhǎng)度的數(shù)字串前導(dǎo)補(bǔ)零
- 3脱拼、兩長(zhǎng)整形數(shù)字的字串從個(gè)位開始,向十位坷备,百位....循環(huán)相加
- 4熄浓、并把上次的十位進(jìn)數(shù)加入本次個(gè)位數(shù),再以字符串形式組合
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String result="";
int n = sc.nextInt();
for(int i = 0; i < n; i++){
String input=sc.next();
if(result.equals("")) {
result=input;
}
else {
result=addLong(result,input);
}
}
System.out.println(result);
}
private static String addLong(String n1, String n2) {
int n1Length=n1.length();
int n2Length=n2.length();
int maxLength=n1Length>n2Length?n1Length:n2Length;
for(int i=0;i<maxLength-n1Length;i++) {
n1="0"+n1;
}
for(int i=0;i<maxLength-n2Length;i++) {
n2="0"+n2;
}
String addResult="";
int js=0;
int gs=0;
for(int i=maxLength-1;i>-1;i--) {
int v1=Integer.parseInt(String.valueOf(n1.charAt(i)));
int v2=Integer.parseInt(String.valueOf(n2.charAt(i)));
int v=v1+v2;
gs=v%10;
addResult=(gs+js)+addResult;
js=v/10;
}
if(js>0) {
addResult=String.valueOf(js)+addResult;
}
return addResult;
}