2020/7/1
问题
Calculate a+b and output the sum in standard format – that is, the digits must be separated into groups of three by commas (unless there are less than four digits). Input Specification: Each input file contains one test case. Each case contains a pair of integers a and b where −106≤a,b≤106. The numbers are separated by a space. Output Specification: For each test case, you should output the sum of a and b in one line. The sum must be written in the standard format. 简单来说,求a+b的和,使和每隔3位加一个","
知识点
for(int i
=0,j
=n
-1;i
<j
;i
++,j
--){
String c
=result
[i
];
result
[i
]=result
[j
];
result
[j
]=c
;
}
java1.0(各种倒叙转换)
import java
.util
.*
;
public class Main{
public static void main(String
[] args
){
Scanner sc
=new Scanner(System
.in
);
int a
=sc
.nextInt();
int b
=sc
.nextInt();
int sum
=a
+b
;
String tmp
=""+sum
;
int n
=tmp
.length();
String
[] temp
=tmp
.split("");
String
[] result
=temp
;
if(n
>3){
for(int i
=0,j
=n
-1;i
<j
;i
++,j
--){
String c
=result
[i
];
result
[i
]=result
[j
];
result
[j
]=c
;
}
ArrayList
<String> str
=new ArrayList<String>();
int count
=0;
for(int i
=0;i
<n
-1;i
++){
str
.add(result
[i
]);
if ((i
+1)%3==0){
str
.add(",");
}
}
str
.add(result
[n
-1]);
String
[] strArray
= str
.toArray(new String[str
.size()]);
String
[] strArray1
=strArray
;
for(int i
=0,j
=strArray1
.length
-1;i
<j
;i
++,j
--){
String c
=strArray1
[i
];
strArray1
[i
]=strArray1
[j
];
strArray1
[j
]=c
;
}
for (int i
=0;i
<strArray1
.length
;i
++){
System
.out
.print(strArray1
[i
]);
}
}else {
System
.out
.print(sum
);
}
}
}
java2.0
使用(result.length-(i+1))%3==0处理
import java
.util
.*
;
public class Main{
public static void main(String
[] args
){
Scanner sc
=new Scanner(System
.in
);
String
[] tmp
=sc
.nextLine().split(" ");
int a
=Integer
.parseInt(tmp
[0]);
int b
=Integer
.parseInt(tmp
[1]);
int sum
=a
+b
;
char[] result
=String
.valueOf(sum
).toCharArray();
if(result
.length
>3){
for(int i
= 0;i
<result
.length
;i
++) {
if((result
.length
-(i
+1))%3==0 && i
!=result
.length
-1 && result
[i
]!='-'){
System
.out
.print(result
[i
]);
System
.out
.print(",");
}else {
System
.out
.print(result
[i
]);
}
}
}else {
for(int i
=0;i
<result
.length
;i
++)
System
.out
.print(result
[i
]);
}
}
}