# Daily Challenge #119 - Adding Big Numbers

### dev.to staff twitter logo Nov 18 '19・1 min read

Daily Challenge (161 Part Series)

We need to sum big numbers and we require your help.

Write a function that returns the sum of two numbers. The input numbers are strings and the function must return a string.

Example:

`add("123", "321"); -> "444"`
`add("11", "99"); -> "110"`

Notes:

• The input numbers are big.
• The input is a string of only digits
• The numbers are positives

This challenge comes from Becojo on CodeWars. Thank you to CodeWars, who has licensed redistribution of this challenge under the 2-Clause BSD License!

Want to propose a challenge idea for a future post? Email yo+challenge@dev.to with your suggestions!

DISCUSS (16) Typescript includes tests

``````export const add = (a: string, b: string): string => {
const re = /^\d+\$/
if (!re.test(a) || !re.test(b)) {
throw new Error(`{a} and {b} must be positive integers`)
}

const result = []
a = a
.split('')
.reverse()
.join('')
b = b
.split('')
.reverse()
.join('')
let carry = 0
for (let i = 0; i < Math.max(a.length, b.length); i++) {
const a_ = a.length > i ? parseInt(a[i]) : 0
const b_ = b.length > i ? parseInt(b[i]) : 0
let sum = a_ + b_ + carry
carry = Math.floor(sum / 10)
if (carry !== 0) {
sum = sum % 10
}
result.push(String(sum))
}
if (carry > 0) {
result.push(carry)
}
return result.reverse().join('')
}
``````

Test

``````import { add } from '.'

it('should throw an error if numbers are not all digits', () => {
})

it('should return sum of two numbers', () => {
})

it('should return sum of two really big numbers', () => {
'1000000002019999999999',
)
})
``````

Python for arbitrarily large numbers represented as strings:

``````def large_sum(a: str, b: str) -> str:

if len(b) < len(a):
return large_sum(b, a)

alist = [int(c) for c in reversed(a)]
blist = [int(c) for c in reversed(b)]

for _ in range(0, len(alist) - len(blist)):
blist.append(0)

overflow = 0
output = []
for ax, bx in zip(alist, blist):
sumval = ax + bx + overflow
overflow = int((sumval) / 10)
output.append(sumval % 10)

if overflow != 0:
output.append(overflow)

return "".join(str(i) for i in reversed(output))

print(large_sum("1234", "3456"))
print(
large_sum(
"1234567890123456789012345678901234567890",
"456789012345678901234567890123456789012345678901234567890123",
)
)
print(large_sum("44", "2"))

``````

Rust:

``````fn add(num1: &str, num2: &str) -> Result<String, String> {
const ZERO_CHAR: u8 = '0' as u8;
let mut reversed_result = Vec::<u8>::new();
let max_digits = num1.len().max(num2.len());

macro_rules! convert_num {
(\$num:expr) => {
\$num.chars().rev().chain(['0'].iter().cloned().cycle())
}
}

let digits1 = convert_num!(num1);
let digits2 = convert_num!(num2);

let mut carry = 0;
for (digit1, digit2) in digits1.zip(digits2).take(max_digits) {
fn digit_to_numeric(digit: char) -> Result<u8, String> {
if '0' <= digit && digit <= '9' {
Ok(digit as u8 - ZERO_CHAR)
} else {
Err(format!("{:?} is not a digit", digit))
}
}

let digit1 = digit_to_numeric(digit1)?;
let digit2 = digit_to_numeric(digit2)?;

let digit_sum = digit1 + digit2 + carry;
carry = digit_sum / 10;
assert!(carry < 10);
reversed_result.push(digit_sum % 10 + ZERO_CHAR);
}
if 0 < carry {
reversed_result.push(carry + ZERO_CHAR);
}
reversed_result.reverse();
}
``````

Javascript

``````add = (x, y) => {
const l = Math.max(x.length, y.length);
const r = Array(l).fill().reduce(
(a, _, i) => [
(a + +(x[x.length - 1 - i] || '0') + +(y[y.length - 1 - i] || '0')) % 10 + a,
+((a + +(x[x.length - 1 - i] || '0') + +(y[y.length - 1 - i] || '0')) > 9)
],
['', 0]);
return '' + (r ? r : '') + r
}
``````

Golang

``````package main

import (
"fmt"
"math/big"
)

func main() {
}

n1 := new(big.Int)
n1, ok := n1.SetString(s1, 10)
if !ok {
return "string was not an integer"
}

n2 := new(big.Int)
n2, ok = n2.SetString(s2, 10)
if !ok {
return "string was not an integer"
}

result := new(big.Int)

return result.String()
}
``````

Swift function :

``````func sum(first: String, second: String) -> String {
return "\((Int(first) ?? 0) + (Int(second) ?? 0))"
}
``````

And with a closure :

``````let _ = { (first: String, second: String) -> String in
"\((Int(first) ?? 0) + (Int(second) ?? 0))"
}
``````

# python

``````def add(a, b):
return (f'{int(a)+int(b)}')
``````

Classic DEV Post from Oct 30 '18

## Relearn You a Haskell (Part 1: The Basics)  