资讯专栏INFORMATION COLUMN

[LeetCode] 415. Add Strings

罗志环 / 1481人阅读

Problem

Given two non-negative integers num1 and num2 represented as string, return the sum of num1 and num2.

Note:

The length of both num1 and num2 is < 5100.
Both num1 and num2 contains only digits 0-9.
Both num1 and num2 does not contain any leading zero.
You must not use any built-in BigInteger library or convert the inputs to integer directly.

Solution
class Solution {
    public String addStrings(String num1, String num2) {
        if (num1 == null || num1.length() == 0) return num2;
        if (num2 == null || num2.length() == 0) return num1;
        
        int i = num1.length()-1, j = num2.length()-1;
        StringBuilder sb = new StringBuilder();
        int carry = 0;
        while (i >= 0 && j >= 0) {
            int n1 = num1.charAt(i--)-"0";
            int n2 = num2.charAt(j--)-"0";
            System.out.println(n1+" "+n2);
            int sum = n1+n2+carry;
            sb.append(sum%10);
            carry = sum/10;
        }
        while (i >= 0) {
            int n = num1.charAt(i--)-"0";
            int sum = n+carry;
            sb.append(sum%10);
            carry = sum/10;
        }
        while (j >= 0) {
            int n = num2.charAt(j--)-"0";
            int sum = n+carry;
            sb.append(""+sum%10);
            carry = sum/10;
        }
        if (carry != 0) sb.append(carry);
        sb.reverse();
        return sb.toString();
    }
}

文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。

转载请注明本文地址:https://www.ucloud.cn/yun/77293.html

相关文章

  • LeetCode 攻略 - 2019 年 7 月下半月汇总(100 题攻略)

    摘要:月下半旬攻略道题,目前已攻略题。目前简单难度攻略已经到题,所以后面会调整自己,在刷算法与数据结构的同时,攻略中等难度的题目。 Create by jsliang on 2019-07-30 16:15:37 Recently revised in 2019-07-30 17:04:20 7 月下半旬攻略 45 道题,目前已攻略 100 题。 一 目录 不折腾的前端,和咸鱼有什么区别...

    tain335 评论0 收藏0
  • 前端 | 每天一个 LeetCode

    摘要:在线网站地址我的微信公众号完整题目列表从年月日起,每天更新一题,顺序从易到难,目前已更新个题。这是项目地址欢迎一起交流学习。 这篇文章记录我练习的 LeetCode 题目,语言 JavaScript。 在线网站:https://cattle.w3fun.com GitHub 地址:https://github.com/swpuLeo/ca...我的微信公众号: showImg(htt...

    张汉庆 评论0 收藏0
  • 43. Multiply Strings

    摘要:是最高位代表进位,表示本位。就是本位的乘积加上本位已有的值。进位就是除以的余数本位就是剩下的个位数。 43 Multiply Strings 关键词,进位。 public class Solution { public String multiply(String num1, String num2) { int m = num1.length(), n = n...

    fsmStudy 评论0 收藏0
  • [Leetcode] Isomorphic Strings 同构字符串

    摘要:最新更新思路和其他语言请访问哈希表法复杂度时间空间思路用一个哈希表记录字符串中字母到字符串中字母的映射关系,一个集合记录已经映射过的字母。或者用两个哈希表记录双向的映射关系。这里不能只用一个哈希表,因为要排除这种多对一的映射。 Isomorphic Strings 最新更新思路和其他语言请访问:https://yanjia.me/zh/2018/11/... Given two st...

    antz 评论0 收藏0
  • [Leetcode] Encode and Decode Strings 字符串编解码

    摘要:记录长度法复杂度时间空间思路本题难点在于如何在合并后的字符串中,区分出原来的每一个子串。这里我采取的编码方式,是将每个子串的长度先赋在前面,然后用一个隔开长度和子串本身。这样我们先读出长度,就知道该读取多少个字符作为子串了。 Encode and Decode Strings Design an algorithm to encode a list of strings to a s...

    gself 评论0 收藏0

发表评论

0条评论

罗志环

|高级讲师

TA的文章

阅读更多
最新活动
阅读需要支付1元查看
<