【一次过】Lintcode 655. 大整数加法

 

以字符串的形式给出两个非负整数 num1 和 num2,返回 num1 和 num2 的和。

样例

给定 num1 = "123",num2 = "45"
返回 "168"

解题思路:

    按位相加即可。注意最后的进位需要考虑。

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
        char[] nums1 = num1.toCharArray();
        char[] nums2 = num2.toCharArray();
        StringBuilder sb = new StringBuilder();
        int cnt = 0;
        
        int i=nums1.length-1, j=nums2.length-1;
        while(i >=0 || j >= 0){
            while(i >=0 && j >= 0){
                int temp = nums1[i] - '0' + nums2[j] - '0' + cnt;
                sb.append(temp%10);
                cnt = temp / 10;
                i--;
                j--;
            }
            
            while(i >= 0){
                int temp = nums1[i] - '0' + cnt;
                sb.append(temp%10);
                cnt = temp / 10;
                i--;
            }
            
            while(j >= 0){
                int temp =  nums2[j] - '0' + cnt;
                sb.append(temp%10);
                cnt = temp / 10;
                j--;
            }
        }
        
        if(cnt != 0)
            sb.append(cnt);
        
        return sb.reverse().toString();
    }
}

 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值