Path: csiph.com!v102.xanadu-bbs.net!xanadu-bbs.net!feeder.erje.net!eu.feeder.erje.net!eternal-september.org!feeder.eternal-september.org!mx02.eternal-september.org!.POSTED!not-for-mail From: Ben Bacarisse Newsgroups: comp.lang.javascript Subject: Re: Bignumb addition function, suggestion improvements. Date: Sat, 14 Mar 2015 13:41:30 +0000 Organization: A noiseless patient Spider Lines: 75 Message-ID: <87fv97u25x.fsf@bsb.me.uk> References: Mime-Version: 1.0 Content-Type: text/plain Injection-Info: mx02.eternal-september.org; posting-host="017616aa25f81ec581c44d76d61ba2f3"; logging-data="12032"; mail-complaints-to="abuse@eternal-september.org"; posting-account="U2FsdGVkX181lT6zD7BpEJF0ksbI89M8xogDoV5aCLg=" Cancel-Lock: sha1:aF7AhUsNcfxpzWekGawsnF2HLho= sha1:13hnIGWBygkIvYJ1T+lDqbppYGs= X-BSB-Auth: 1.26e70a9a77b46c3a7f24.20150314134130GMT.87fv97u25x.fsf@bsb.me.uk Xref: csiph.com comp.lang.javascript:27032 jonas.thornvall@gmail.com writes: > I just wrote a big numb addition function this morning, it is a bit > silly and naive, not pure string not pure integer. I think it is > correct, but i may have missed leading last digit. Yes, you do miss the leading digit in some cases. And it's only for positive numbers. > Suggestions to write it shorter and more clear, but keeping the naive > approach appreciated. > > String.prototype.digitValueAt = function (pos) { var d = this.charCodeAt(pos); return isNaN(d) ? 0 : d - 48; } function naiveAddX(strOne, strTwo) { var i1 = strOne.length, i2 = strTwo.length, result = "", carry = 0; while (i1 > 0 || i2 > 0 || carry > 0) { var dsum = strOne.digitValueAt(--i1) + strTwo.digitValueAt(--i2) + carry; if (dsum >= 10) { dsum -= 10; carry = 1; } else carry = 0; result = dsum + result; } return result; } You could also build a result array and create the string on one go. That's probably faster. -- Ben.