题解 | #大数加法#

大数加法

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

思路很简单:
例如 1 + 9999999,我们需要从最后加呗,先判断是否进位,在判断当前位置。

import java.util.*;


public class Solution {
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     * 计算两个数之和
     * @param s string字符串 表示第一个整数
     * @param t string字符串 表示第二个整数
     * @return string字符串
     */
    public String solve (String s, String t) {
        // write code here
        int m = s.length();
        int n = t.length();
        int len = m > n ? m : n;
        int[] temp = new int[len + 1];
        int index = len;
        int left = m-1;
        int right = n-1;
        while(left >=0 && right>=0){
            int temps = temp[index]+ (s.charAt(left--) - '0') + (t.charAt(right--) - '0');
            temp[index-1] = temps/10;
            temp[index--] = temps%10;

        }
        while(left >=0){
            int temps = temp[index]+ (s.charAt(left--) - '0');
            temp[index-1] = temps/10;
            temp[index--] = temps%10;
        }
          while(right >=0){
            int temps = temp[index]+ (t.charAt(right--) - '0');
            temp[index-1] = temps/10;
            temp[index--] = temps%10;
        }
        StringBuffer sb = new StringBuffer();
        index = 0;
        while(index<=len && temp[index] == 0){
            index++;
        }
        for(int i = index;i<=len;i++){
            sb.append(temp[i]);
        }
        return sb.toString().equals("") ? "0" : sb.toString();
    }
}
全部评论

相关推荐

书海为家:实习是成为大厂正式员工很好的敲门砖,看您的简历中有一段实习经历,挺好的。我来给一点点小建议,因为毕竟还在学校不像工作几年的老鸟有丰富的项目经验,面试官在面试在校生的时候更关注咱们同学的做事逻辑和思路,所以最好在简历中描述下自己实习时做过项目的完整过程,比如需求怎么来的,你对需求的解读,你想到的解决办法,遇到困难如何找人求助,最终项目做成了什么程度,你从中收获了哪些技能,你有什么感悟。
点赞 评论 收藏
分享
评论
1
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务