Add two large numbers

    0

    0

    pavan koka

    The code defines a function called add which takes two arguments, A and B.

    The first two lines of code iterate through the characters in A and B, and collect the number of characters between them.

    The next three lines calculate the sum of the absolute value of each character. This is done to stop the sum from getting too large if there are lots of small numbers in the sum.

    The final line of code returns the sum.

    function add(A, B) {
      const AL = A.length
      const BL = B.length
      const ML = Math.max(AL, BL)
    
      let carry = 0, sum = ''
    
      for (let i = 1; i <= ML; i++) {
        let a = +A.charAt(AL - i)
        let b = +B.charAt(BL - i)
    
        let t = carry + a + b
        carry = t/10 |0
        t %= 10
    
        sum = (i === ML && carry)
          ? carry*10 + t + sum
          : t + sum
      }
    
      return sum
    }
    Codiga Logo
    Codiga Hub
    • Rulesets
    • Playground
    • Snippets
    • Cookbooks
    soc-2 icon

    We are SOC-2 Compliance Certified

    G2 high performer medal

    Codiga – All rights reserved 2022.