Programming Languages war
Python, PHP, Javascrip (Nodejs)
Add Two Numbers

Programming Languages war Python, PHP, Javascrip (Nodejs) Add Two Numbers

Hey my friends, a new post about this war. I don't know which is better, but I'll try to figure it out. I hope y'all enjoy this series. Here we go!

This is a challenge of leetcode.com I made this challenge with python3, and next I made PHP and Javacript the same way.

Problem:

You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order, and each of their nodes contains a single digit. Add the two numbers and return the sum as a linked list.

You may assume the two numbers do not contain any leading zero, except the number 0 itself.

Example 1:

Input: l1 = [2,4,3], l2 = [5,6,4] Output: [7,0,8] Explanation: 342 + 465 = 807.

Python

I receive two objects and I have to add, I used "while" to iterate the object and pass to list, it's easier manipulate the number of this way, I reverse the list with the method "reverse()", and turn list to string and then to integer, I add both numbers and reverse again and return the list converted to ListNode Object.

# Definition for singly-linked list.
class ListNode:
  def __init__(self, x):
    self.val = x
    self.next = None

class Solution:
  def addTwoNumbers(self, l1, l2):
    al = list()
    bl = list()

    while l1 or l2:   
      (al.append(l1.val) if l1 else None)
      (bl.append(l2.val) if l2 else None)      
      l1 = (l1.next if l1 else None)
      l2 =(l2.next if l2 else None)

    al.reverse()
    bl.reverse()
    str1 = ''.join(map(str, al))
    str2 = ''.join(map(str, bl))
    result = int(str1) + int(str2)
    result = list(str(result))
    result.reverse()
    return self.createList(ListNode(0), result, 0)

  def createList(self, node, list, pos):
    if node.val == 0:
      if len(list) > pos:
        node.val = list[pos]
        self.createList(node, list, pos+1)
    else:
      if len(list) > pos:
        node.next = ListNode(list[pos])
        if(len(list) > pos+1):
          self.createList(node.next, list, pos+1)
        else:
          return node
    return node


sol = Solution()
a = sol.createList(ListNode(0), [2,4,3], 0)
b = sol.createList(ListNode(0), [5,6,4], 0)
solve = sol.addTwoNumbers(a, b)

print(solve)

PHP

I receive two objects and I have to add, I used "while" to iterate the object and to turn to array, it's easier to manipulate the number of this way. I try to use reverse here, that exist a method for that, but when I try to send my solution is not successful in all cases. For example an array with length 31, because when I turn this array in a number return a number like 1E+30, then I can't solve that, but I resolve the challenge the other way. I validate what an array is longer, so, I add but to left to right and validate if the result is gran than 9 and save the number in a new array and return the array converted to ListNode Object.

<?php
class ListNode
{
    public $val  = 0;
    public $next = null;
    public function __construct($val = 0, $next = null)
    {
        $this->val  = $val;
        $this->next = $next;
    }
}

class Solution
{
    public function addTwoNumbers($l1, $l2)
    {
        $al = array();
        $bl = array();

        while ($l1) {
            $al[] = $l1->val;
            $l1   = $l1->next ? $l1->next : null;
        }

        while ($l2) {
            $bl[] = $l2->val;
            $l2   = $l2->next ? $l2->next : null;
        }
        if (count($al) > count($bl) || count($al) == count($bl)) {
            $pending = 0;
            for ($i = 0; $i < count($al); $i++) {
                $a = $al[$i];
                $b = !empty($bl[$i]) ? $bl[$i] : 0;
                $r = $a + $b + $pending;
                if ($r > 9) {
                    $result[] = (strval($r))[1];
                    $pending  = (strval($r))[0];
                } else {
                    $result[] = strval($r);
                    $pending  = 0;
                }

            }
            if($pending){
                $result[] = $pending;
            }
        } else {
            $pending = 0;
            for ($i = 0; $i < count($bl); $i++) {
                $a = $bl[$i];
                $b = !empty($al[$i]) ? $al[$i] : 0;
                $r = $a + $b + $pending;
                if ($r > 9) {
                    $result[] = (strval($r))[1];
                    $pending  = (strval($r))[0];
                } else {
                    $result[] = strval($r);
                    $pending  = 0;
                }

            }
            if($pending){
                $result[] = $pending;
            }
        }

        return $this->createList(new ListNode(0), $result, 0);

    }
    public function createList($node, $arr, $pos)
    {
        if ($node->val == 0 && $pos == 0) {

            if (count($arr) > $pos) {
                $node->val = $arr[$pos];
                $this->createList($node, $arr, $pos + 1);
            }
        } else {

            if (count($arr) > $pos) {
                $node->next = new ListNode($arr[$pos]);
                if (count($arr) > $pos + 1) {
                    $this->createList($node->next, $arr, $pos + 1);
                } else {
                    return $node;
                }

            }
        }
        return $node;
    }
}

$sol = new Solution();
$a   = $sol->createList(new ListNode(0), [2,4,9], 0);
$b   = $sol->createList(new ListNode(0), [5,6,4,9], 0);

$solve = $sol->addTwoNumbers($a, $b);

var_dump($solve);


?>

Javascript

I receive two objects and I have to add, I used "while" to iterate the object and to turn to array, it's easier to manipulate the number of this way, I try to use reverse here, that exist a method for that, but when to try to send my solution is not successful in all cases. For example an array with length 31, because when I turn this array in a number return a number like 1E+30 the same that PHP, then I can't solve that, but I resolve the challenge the other way. I validate what an array is longer, so, I add but to left to right and validate if the result is gran than 9 and save the number in a new array and return the array converted to ListNode Object.

class ListNode {
  constructor(val = 0, next = null) {
    this.val = val === undefined ? 0 : val;
    this.next = next === undefined ? null : next;
  }
}

class Solution {
  addTwoNumbers(l1, l2) {
    let al = [];
    let bl = [];

    while (l1) {
      al.push(l1.val);
      l1 = l1.next ? l1.next : null;
    }

    while (l2) {
      bl.push(l2.val);
      l2 = l2.next ? l2.next : null;
    }
    let pending = 0;
    let result = [];
    if (al.length > bl.length || al.length == bl.length) {
      for (let i = 0; i < al.length; i++) {
        let a = al[i];
        let b = bl[i] ? bl[i] : 0;
        let r = a + b + parseInt(pending);
        if (r > 9) {
          result.push(String(r)[1]);
          pending = String(r)[0];
        } else {
          result.push(String(r));
          pending = 0;
        }
      }
      if (pending) {
        result.push(pending);
      }
    }
    if (al.length < bl.length) {
      for (let i = 0; i < bl.length; i++) {
        let a = bl[i];
        let b = al[i] ? al[i] : 0;
        let r = a + b + parseInt(pending);
        if (r > 9) {
          result.push(String(r)[1]);
          pending = String(r)[0];
        } else {
          result.push(String(r));
          pending = 0;
        }
      }
      if (pending) {
        result.push(pending);
      }
    }


    return this.createList(new ListNode(0), result, 0);
  }
  createList(node, arr, pos) {
    if (node.val == 0 && pos == 0) {
      if (arr.length > pos) {
        node.val = arr[pos];
        this.createList(node, arr, pos + 1);
      }
    } else {
      if (arr.length > pos) {
        node.next = new ListNode(arr[pos]);
        if (arr.length > pos + 1) {
          this.createList(node.next, arr, pos + 1);
        } else {
          return node;
        }
      }
    }
    return node;
  }
}

const sol = new Solution();
const a = sol.createList(new ListNode(0), [2, 4, 3], 0);
const b = sol.createList(new ListNode(0), [5, 6, 4], 0);
const solve = sol.addTwoNumbers(a, b);

console.log(solve);

Conclusion

Structure: Python: I don't have problem to manipulate long integer, PHP and Javascript I have to change my first solution, I don't change my python way to be like PHP and Javascript because was a little slower in Python. Lines: Python: 47, PHP: 107, Javascript: 87 Time to execution: Python: 72 ms, PHP: 28 ms, Javascript: 144 ms Memory Usage: Python: 14.5 MB, PHP: 15.8 MB, Javascript: 46.6 MB

Would you like that I write about more challenges?

I hope you enjoy my post and remember that I am just a Dev like you!