Skip to content

Prepare For Coder Interview – Denny

  • Basic
  • Medium
  • Hard
  • Architect
  • Life

LeetCode: Add Strings

Posted on January 10, 2018July 26, 2020 by braindenny

Add 2 strings of big numbers



Similar Problems:

  • LeetCode: Add to Array-Form of Integer
  • LintCode: K Decimal Addition
  • Additive Number

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.

Github: code.dennyzhang.com

Credits To: leetcode.com

Leave me comments, if you have better ways to solve.


// https://code.dennyzhang.com/add-strings
// Basic Ideas: 
//  Handle carry
//  Only stop when both strings have finished
// Complexity: Time O(n), Space O(n)
import "strconv"
func addStrings(num1 string, num2 string) string {
    carry, res := 0, ""
    for i, j:= len(num1)-1, len(num2)-1;
        i>=0 || j>=0 || carry!=0; 
        i, j = i-1, j-1 {
        v1, v2, v := 0, 0, 0
        if i>=0 { v1, _ = strconv.Atoi(string(num1[i])) }
        if j>=0 { v2, _ = strconv.Atoi(string(num2[j])) }
        v = v1+v2+carry
        if v>=10 {
            carry = 1
            v -= 10
        } else {
            carry = 0
        }
        res = strconv.Itoa(v)+res
    }
    return res
}
linkedin
github
slack

Post Views: 5
Posted in BasicTagged #bignumber, #classic

Post navigation

LeetCode: Count Complete Tree Nodes
LeetCode: First Bad Version

Leave a Reply Cancel reply

Your email address will not be published.

Tags

#array #backtracking #bfs #binarytree #bitmanipulation #blog #classic #codetemplate #combination #dfs #dynamicprogramming #game #graph #greedy #heap #inspiring #interval #linkedlist #manydetails #math #palindrome #recursive #slidingwindow #stack #string #subarray #trie #twopointer #twosum binarysearch editdistance hashmap intervaldp knapsack monotone oodesign presum rectangle redo review rotatelist series sql treetraversal unionfind

Recent Posts

  • a
  • a
  • a
  • a
  • a

Recent Comments

    Archives

    Categories

    • Amusing
    • Basic
    • Easy
    • Hard
    • Life
    • Medium
    • Resource
    • Review
    • Series
    • Uncategorized
    Proudly powered by WordPress | Theme: petals by Aurorum.