我会加分的,提个思路都行,目前做了个乘法和加法,但是现在对除法没有什么思路。以下是我编写的功能:publicclassCalculator{publicstaticStringmulti(Strings1,Strings2){if(s1==nu...
我会加分的,提个思路都行,目前做了个乘法和加法,但是现在对除法没有什么思路。以下是我编写的功能:
public class Calculator {
public static String multi(String s1,String s2){
if(s1 == null || s2 == null){
return "0";
}
char c1[] = s1.toCharArray();
char c2[] = s2.toCharArray();
for(int i=0;i
if(i==0){
if(c1[i] !='-' && c1[i] != '+' && !(c1[i]>='0' && c1[i]<='9')){
throw new RuntimeException("你要计算的数字不合法!");
}
}else{
if(!(c1[i]>='0' && c1[i]<='9')){
throw new RuntimeException("你要计算的数字不合法!");
}
}
}
for(int i=0;i
if(i==0){
if(c2[i] !='-' && c2[i] != '+' && !(c2[i]>='0' && c2[i]<='9')){
throw new RuntimeException("你要计算的数字不合法!");
}
}else{
if(!(c2[i]>='0' && c2[i]<='9')){
throw new RuntimeException("你要计算的数字不合法!");
}
}
}
String sign1 = "";
String sign2 = "";
if(s1.charAt(0)>='0' && s1.charAt(0)<='9'){
sign1="+";
}else{
sign1 = s1.substring(0,1);
s1 = s1.substring(1);
}
if(s2.charAt(0)>='0' && s2.charAt(0)<='9'){
sign2 = "+";
}else{
sign2 = s2.substring(0,1);
s2 = s2.substring(1);
}
StringBuffer buffer = new StringBuffer();
Long[][] number = new Long[s2.length()][s1.length()+s2.length()];
for(int i=0;i
int t = Integer.parseInt(s2.substring(s2.length()-(i+1),s2.length()-i));
int temp = 0;
int count = 0;
for(int j=number[i].length-1;j>=0;j--){
if(count
int cols = Integer.parseInt(s1.substring(s1.length()-(count+1),s1.length()-count));
number[i][j-i] = new Long( ((cols*t)%10)+temp);
temp = cols*t/10;
}else if(temp !=0){
number[i][j-i] = new Long(temp);
temp = 0;
}
count++;
}
}
int temp = 0;
for(int i=(s1.length()+s2.length())-1;i>=0;i--){
int t = 0;
for(int j=0;j
if(number[j][i] != null){
t+=number[j][i];
}
}
buffer.append(""+(t%10+temp));
temp = t/10;
}
buffer = buffer.reverse();
String result = buffer.toString();
while(result.charAt(0) == '0' && result.length() !=1){
result = result.substring(1);
}
if(!sign1.equals(sign2)){
result = "-"+result;
}
return result;
}
public static String add(String s1,String s2){
//因为字数超过限制,所以没有上传
return "还没有实现!";
}
public static void main(String[] args){
System.out.println(Calculator.add("-755334311424342","-9222012"));
BigInteger big1 = new BigInteger("-755334311424342");
BigInteger big2 = new BigInteger("-9222012");
System.out.println(big1.add(big2)); System.out.println(Calculator.multi("-23423403504534534563","23222222222222222222222222222222222"));
}
}
-----------result-------------
-755334320646354
-755334320646354
-543943470131721017861316196131010101010101010101010101019518951801921211121215658986
展开