lintCode655:大整数相加

来源:互联网 发布:js 取数组前几个 编辑:程序博客网 时间:2024/06/02 05:44
public class Solution {    /*     * @param num1: a non-negative integers     * @param num2: a non-negative integers     * @return: return sum of num1 and num2     */     public String addStrings(String num1, String num2) {        // write your code here        String temp = "";        String temp2 = "";        int jingwei = 0;        StringBuffer result = new StringBuffer();        Stack<String> stack = new Stack<>();        if(num1.length()<num2.length()){            temp = num1;            temp2 = num2;        }else{            temp = num2;            temp2 = num1;        }        int j =temp2.length()-1;        for(int i = temp.length()-1;i>=0;i--,j--){            int numTemp1 = temp.charAt(i) - '0';            int numTemp2 = temp2.charAt(j) - '0';            int resultTemp =(numTemp1+numTemp2+jingwei);            if(resultTemp<10){                stack.push(resultTemp+"");                jingwei = 0;            }else{                stack.push((resultTemp-10)+"");                jingwei = 1;            }        }        for(int i = j;i>=0;i--){            int resultTemp = temp2.charAt(i)-'0'+jingwei;            if(resultTemp<10){                stack.push(resultTemp+"");                jingwei = 0;            }else {                stack.push((resultTemp - 10) + "");                jingwei = 1;            }        }        //判断是否需要进位        if(jingwei == 1){            stack.push(1+"");        }        while(!stack.empty()){            result.append(stack.pop());        }        return result.toString();    }}

原创粉丝点击