LeetCode 2兩大數相加

描述:兩個大數相加

package com.jd.leetcodedemo;


/**
 * LeetCode第二題(兩數相加)
 * @author tianchuangxin1
 * @date 2019-02-28 20:29
 */
public class LeetCode_2 {


    /**
     * 計算兩數相加(假設整型數組中的每個數>=0,<=9)
     *
     *  3-2-4  arr1
     *  4-2-1  arr2
     *
     *  return 7-4-5
     *
     * @param arr1
     * @param arr2
     * @return
     */
    public static String getSolution(int[] arr1 ,int[] arr2){

        //思路描述,從末位開始相加,得到最大的數組,然後遍歷數組每個元素,大於10的前一位加一,當前減10取個位數
        String result="";
        int forword=0;
        int j=arr1.length-1;
        int k=arr2.length-1;
        for (int i=0;i<Math.max(arr1.length,arr2.length);i++){
            int resultInt=0;
            if (j>=0){
                if (k>=0){
                    resultInt=arr1[j]+arr2[k]+forword;
                    if (resultInt>=10){
                        resultInt=resultInt-10;
                        forword=1;
                    }else{
                        forword=0;
                    }
                    result=resultInt+result;
                }else {
                    result=(arr1[j]+forword)+result;
                    forword=0;
                }
            }else{
                result=(arr2[k]+forword)+result;
                forword=0;
            }
            j--;
            k--;
        }
        return forword==0?result:(forword+result);
    }



}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章