两个大数相加的三种实现方法

方法一:

import java.math.BigDecimal;



/**
 * 两个大数相加
 *
 * @author 
 * @version $Id: BigNumberAdd.java, v 0.1 2014年8月18日 下午2:13:20 
 */
public class BigNumberAdd1 {
    
    public static void main(String[] args) {
        
        String num1 = "34646313135453431";
        String num2 = "999999999121111";
        
        int len1 = num1.length();
        int len2 = num2.length();
        
        if(len1 > len2){
            for(int i=0; i=0; i--){
            if(i == result.length-1 && result[i] == 0) continue;
            System.out.print(result[i]);
        }
        
        System.out.println();
        System.out.println("****************以下为对照结果******************");
        
        BigDecimal b1 = new BigDecimal(num1);
        BigDecimal b2 = new BigDecimal(num2);
        
        BigDecimal b3 = b1.add(b2);
        System.out.println(b3);
    }
    
    /**
     * 核心方法   两个整型数组相加 
     *
     * @param a
     * @param b
     * @return
     */
    public static int[] add(int[] a,int[] b){
        int maxlen = a.length;
        int[] sum = new int[maxlen + 1];
        for(int i=0; i

 方法二:

public class BigNumberAdd2 {

    public static void main(String[] args) {
        String str1 = "34646313135453431";
        String str2 = "999999999121111";

        int len1 = str1.length();
        int len2 = str2.length();
        if(len1 > len2){
            for(int i=0; i=0; i--){
            int a = str1.charAt(i) - '0';
            int b = str2.charAt(i) - '0';
            int sum = 0;
            if(flag){
                sum  = 1;
            } 
            sum += (a + b);
            if(sum / 10 > 0){
                flag = true;
            } else {
                flag = false;
            }
            result = sum % 10 + result;
        }
        return result;
    }
    
}

 方法三:

public class BigNumberAdd3 {

    public static void main(String[] args) {
        String num1 = "34646313135453431";
        String num2 = "999999999121111";
        
        int len1 = num1.length();
        int len2 = num2.length();
        
        if(len1 > len2){
            for(int i=0; i=0; i--){
            int a = num1.charAt(i) - '0';
            int b = num2.charAt(i) - '0';
            arr[i+1] = a + b; 
        }
        
        for(int i=len1; i>0; i--){
            int temp = arr[i];
            arr[i] = temp % 10;
            arr[i-1] = arr[i-1] + temp / 10;
        }
        String result = toString(arr);
        if(result.charAt(0) == '0') {
            result = result.substring(1);
        }
        System.out.println(result);
    }
    
    public static String toString(int[] arr){
        StringBuilder sb = new StringBuilder();
        for(int i=0; i

 

你可能感兴趣的:(Java基础,java,python)