.大数求差,给两个字符串(1-100位),求他们的差,如果是负数,则输出负数。
如:“1111111111”,“1234678899879"输出:-1233567788768
1 package com.huawei; 2 3 import java.math.BigDecimal; 4 5 public class BigDic 6 { 7 8 public static void main(String[] args) 9 { 10 System.out.println(4-8); 11 System.out.println(sub("23456789234567891234567891111","1234567891234567891234567891111234567891234567891111234567891234567891111")); 12 System.out.println(sub2("23456789234567891234567891111","1234567891234567891234567891111234567891234567891111234567891234567891111")); 13 } 14 private static String sub2(String first, String second) 15 { 16 String res = ""; 17 char[] a = new StringBuilder(first).reverse().toString().toCharArray(); 18 char[] b = new StringBuilder(second).reverse().toString().toCharArray(); 19 int firestLength = first.length(); 20 int secondLength = second.length(); 21 char sign = '+'; 22 boolean jiewei = false; 23 int maxLength = firestLength > secondLength ? firestLength :secondLength; 24 25 if(firestLength < secondLength) 26 { 27 sign='-'; 28 } 29 else if(firestLength == secondLength) 30 { 31 sign = a[a.length-1] > b[b.length-1] ? '+':'-'; 32 } 33 34 // System.out.println("sign="+sign); 35 for(int i = 0;i < maxLength;i++) 36 { 37 38 int f1 = i < firestLength ? a[i] - '0' : 0; 39 int s1 = i < secondLength ? b[i] - '0' : 0; 40 int temp = 0; 41 if(firestLength < secondLength) 42 { 43 s1 = jiewei == true ? s1 - 1 : s1; 44 temp = s1 - f1; 45 jiewei = s1 - f1 < 0 ? true : false; 46 temp = jiewei==true ? temp+10:temp; 47 48 } 49 else 50 { 51 f1 = jiewei == true ? f1 - 1 : 1; 52 temp = f1 - s1; 53 jiewei = f1 - s1 < 0 ? true : false; 54 temp = jiewei==true ? temp+10:temp; 55 } 56 57 res = temp + res; 58 } 59 res = sign =='+' ? res : '-'+res; 60 return res; 61 } 62 public static String sub(String first,String second) 63 { 64 BigDecimal a = new BigDecimal(first); 65 BigDecimal b = new BigDecimal(second); 66 return a.subtract(b).toString(); 67 } 68 }