Skip to content

Instantly share code, notes, and snippets.

@sharmaabhinav
Last active September 7, 2017 11:21
Show Gist options
  • Select an option

  • Save sharmaabhinav/78014f8daa0aba05ac1484863d7c194e to your computer and use it in GitHub Desktop.

Select an option

Save sharmaabhinav/78014f8daa0aba05ac1484863d7c194e to your computer and use it in GitHub Desktop.
function skipLeadingZeros (string) {
var str = ''
var start = 0
var end = string.length
while(start < end && string[start] === '0'){
start ++
}
while(start < end){
str += string[start]
start += 1
}
return str
}
// since input string contain only '0' to '9' we can use parseInt safely
function sumStrings (string1, string2) {
var carry = 0
var ans = ""
var start1
var start2
var digit1
var digit2
string1 = skipLeadingZeros(string1)
string2 = skipLeadingZeros(string2)
start1 = string1.length - 1
start2 = string2.length - 1
while(start1 >= 0 && start2 >= 0) {
digit1 = parseInt(string1[start1])
digit2 = parseInt(string2[start2])
ans += (digit1 + digit2 + carry) % 10
carry = Math.floor( (digit1 + digit2 + carry) / 10 )
start1 -= 1
start2 -= 1
}
while(start1 >= 0) {
digit = parseInt(string1[start1])
ans += (digit + carry) % 10
carry = Math.floor( (digit + carry) / 10)
start1 -= 1
}
while(start2 >= 0) {
digit = parseInt(string2[start2])
ans += (digit + carry) % 10
carry = Math.floor( (digit + carry) / 10)
start2 -= 1
}
if (carry !== 0) {
ans += carry
}
return ans.split('').reverse().join('')
}
function testRunner (expectedValue, valueFromTest) {
// check type also use ===
if (expectedValue === valueFromTest) {
return 'passed'
} else {
return 'failed'
}
}
// test cases for methods
testRunner(skipLeadingZeros('000123'), '123')
testRunner(skipLeadingZeros('001023'), '1023')
testRunner(skipLeadingZeros('000120300'), '120300')
testRunner(sumStrings('1', '2'), '3')
testRunner(sumStrings('800', '9567'), '10367')
testRunner(sumStrings('99', '1'), '100')
testRunner(sumStrings('00103', '08567'), '8670')
testRunner(sumStrings('50095301248058391139327916261', '81055900096023504197206408605'), '131151201344081895336534324866')
testRunner(sumStrings('00000000', '8567'), '8567')
testRunner(sumStrings('99999', '99999'), '199998')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment