• [LeetCode] 415. Add Strings


    Given two non-negative integers 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.

    字符串相加。题目即是题意。影子题67,这个题是十进制加法,67题是二进制加法。例子,

    "13" + "79" = "92"

    这个题没有任何算法,考察的是字符串的相关操作。Java和JS的做法略微有一些区别。在Java里面因为有StringBuilder的关系,所以结果里面的每一位上的数字可以被append;JS里面则是用数组代替了StringBuilder的功用。但是两种语言实现的思想是一样的。

    时间O(n)

    空间O(n)

    Java实现

     1 class Solution {
     2     public String addStrings(String num1, String num2) {
     3         int i = num1.length() - 1;
     4         int j = num2.length() - 1;
     5         int carry = 0;
     6         StringBuilder sb = new StringBuilder();
     7         while (i >= 0 || j >= 0 || carry == 1) {
     8             int a = i >= 0 ? num1.charAt(i--) - '0' : 0;
     9             int b = j >= 0 ? num2.charAt(j--) - '0' : 0;
    10             int sum = a + b + carry;
    11             sb.append(sum % 10);
    12             carry = sum / 10;
    13         }
    14         return sb.reverse().toString();
    15     }
    16 }

    JavaScript实现

     1 /**
     2  * @param {string} num1
     3  * @param {string} num2
     4  * @return {string}
     5  */
     6 var addStrings = function(num1, num2) {
     7     let i = num1.length - 1;
     8     let j = num2.length - 1;
     9     let carry = 0;
    10     let res = [];
    11     while (i >= 0 || j >= 0 || carry == 1) {
    12         let digit1 = i < 0 ? 0 : num1.charAt(i) - '0';
    13         let digit2 = j < 0 ? 0 : num2.charAt(j) - '0';
    14         let digitsSum = digit1 + digit2 + carry;
    15         res.push(digitsSum % 10);
    16         carry = Math.floor(digitsSum / 10);
    17         i--;
    18         j--;
    19     }
    20     return res.reverse().join('');
    21 };

    LeetCode 题目总结

  • 相关阅读:
    git 获取之前某个版本
    mysql默认查询顺序
    tp5链式查询fetchSql(true)方法
    微信中关闭网页输入内容时的安全提示
    SourceTree + BeyondCompare 配置 + 使用教程
    SourceTree 免登录跳过初始设置
    git 常规发布流程
    Git常用操作命令
    手动安装phpRedisAdmin
    docker-compose快速搭建lnmp+redis服务器环境
  • 原文地址:https://www.cnblogs.com/cnoodle/p/12571976.html
Copyright © 2020-2023  润新知