题解 | #大数加法#

大数加法

http://www.nowcoder.com/practice/11ae12e8c6fe48f883cad618c2e81475

import java.util.*;


public class Solution {
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     * 计算两个数之和
     * @param s string字符串 表示第一个整数
     * @param t string字符串 表示第二个整数
     * @return string字符串
     */
    public String solve (String s, String t) {
        if(s==null||s.length()==0){
            return t;
        }
        if(t==null||t.length()==0){
            return s;
        }
        Stack<Integer> str = new Stack<Integer>();
        int up_bit = 0;
        char[] cs = s.toCharArray();
        char[] ts = t.toCharArray();
        //从参数栈中取数并相加存到结果栈中
        int i=cs.length;
        int j=ts.length;
		while(i>0||j>0) {
			int i1 = 0;
			int i2 = 0;
			if(i>0) {
				i1 = cs[i-1]-'0';
			}
			if(j>0) {
				i2 = ts[j-1]-'0';
			}
			int tot = i1+i2+up_bit;
			str.push(tot%10);
			up_bit=tot/10;	
            i--;
            j--;
		}
		if(up_bit>0) {
			str.push(up_bit);
		}
        StringBuilder sb = new StringBuilder();
        while(!str.isEmpty()) {
			sb.append(str.pop());
        }
        return sb.toString();
    }
}
全部评论

相关推荐

点赞 评论 收藏
分享
03-18 09:45
莆田学院 golang
牛客749342647号:佬,你这个简历模板是哪个,好好看
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务