前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >LeetCode笔记:415. Add Strings

LeetCode笔记:415. Add Strings

作者头像
Cloudox
发布2021-11-23 15:52:58
2660
发布2021-11-23 15:52:58
举报
文章被收录于专栏:月亮与二进制

问题:

Given two non-negative numbers num1 and num2 represented as string, return the sum of num1 and num2. Note: 1、The length of both num1 and num2 is < 5100. 2、Both num1 and num2 contains only digits 0-9. 3、Both num1 and num2 does not contain any leading zero. 4、You must not use any built-in BigInteger library or convert the inputs to integer directly.

大意:

给出两个字符串形式的非负数num1和num2,返回num1和num2之和。 注意: 1、num1和num2的长度都小于5100。 2、num1和num2都只包含数字0-9。 3、num1和num2都不包含处于首位的0。 4、你不能使用任何内置的大数库或者直接将输入转化成整型。

思路:

题目不允许直接转化成整型去计算,也就是要我们一位一位地将数字加起来实现一次加法了。从两个字符串的最末尾开始去加,注意判断是否要进位,一位位加到两个字符串都遍历完为止,为了速度这里要使用StringBuilder,如果直接用 + 去进行字符拼接就太慢了,注意我们每次对每位数进行加时还是用整型来计算,这还是允许的,不然也太麻烦了,代码比较容易看懂。

代码(Java):

代码语言:javascript
复制
public class Solution {
    public String addStrings(String num1, String num2) {
        if (num1.length() == 0) return num2;
        else if (num2.length() == 0) return num1;
        
        boolean hasUp = false;// 是否进位
        int i = num1.length() - 1;
        int j = num2.length() - 1;
        StringBuilder sb = new StringBuilder();
        while (i >=0 || j >= 0) {
            int n1 = i >= 0 ? num1.charAt(i) - '0' : 0;
            int n2 = j >= 0 ? num2.charAt(j) - '0' : 0;
            int sum = n1 + n2 + (hasUp ? 1 : 0);
            if (sum >= 10) {
                sb.insert(0, Integer.toString(sum - 10));
                hasUp = true;
            } else {
                sb.insert(0, Integer.toString(sum));
                hasUp = false;
            }
            i--;
            j--;
        }
        if (hasUp) sb.insert(0, "1");
        return sb.toString();
    }
}

合集:https://github.com/Cloudox/LeetCode-Record

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2017/11/21 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 问题:
  • 大意:
  • 思路:
  • 代码(Java):
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档