1. 程式人生 > >大數減法(Java)

大數減法(Java)

import java.util.Scanner;


public class Hello {


public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
String s1,s2;
s1=sc.next();
s2=sc.next();
String s=sub(s1,s2);
System.out.println(s);


}
public static String sub(String num1,String num2) {
num1=reverseString(num1);
num2=reverseString(num2);
StringBuilder res=new StringBuilder();
int carry=0;   //carry表示借位
int N1=num1.length();
int N2=num2.length();
int i=0;
for(;i<N2;i++) {
int i1=charToInt(num1.charAt(i));
int i2=charToInt(num2.charAt(i));
int r=i1-i2-carry;
if(r<0) {
carry=1;
r=r+10;
}
else {
carry=0;
}
res.append(r);   //在字串末尾新增內容
     }
for(;i<N1;i++) {
int i1=charToInt(num1.charAt(i));
int r=i1-carry;
if(r<0) {
r=r+10;
carry=1;
}
else {
carry=0;
}
res.append(r);
}


return removeHeadZero(res.reverse().toString());   //例 10000-101


}


static String reverseString(String ori) {
StringBuilder reversed=new StringBuilder(ori);
    reversed.reverse();//字元反轉
    return reversed.toString();
}
static int charToInt(char ch) {
int value=(int)ch-'0';
return value;
}
static String removeHeadZero(String str) {
StringBuilder s = new StringBuilder(str);
for (int i = 0; i<str.length()-1; i++) {
if(str.charAt(i)=='0')
s.deleteCharAt(0);
else break;
}
return s.toString();
}


}