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 19:39:57 +0000 Organization: A noiseless patient Spider Lines: 86 Message-ID: <878uezpdv6.fsf@bsb.me.uk> References: <87fv97u25x.fsf@bsb.me.uk> <531f97ee-89e2-49a6-b9a8-4b11102e998c@googlegroups.com> Mime-Version: 1.0 Content-Type: text/plain; charset=iso-8859-1 Content-Transfer-Encoding: 8bit Injection-Info: mx02.eternal-september.org; posting-host="017616aa25f81ec581c44d76d61ba2f3"; logging-data="29279"; mail-complaints-to="abuse@eternal-september.org"; posting-account="U2FsdGVkX1+Kl125miId3xWv3ouXwC1OnGPlnLOoj8U=" Cancel-Lock: sha1:23nUq75+AVEI1jVESyDUWP8yFBc= sha1:/yKCxhzIGm7Slt5DfoBPTkf1mtc= X-BSB-Auth: 1.fd392b9eb648ebbdcb1c.20150314193957GMT.878uezpdv6.fsf@bsb.me.uk Xref: csiph.com comp.lang.javascript:27036 jonas.thornvall@gmail.com writes: > Den lördag 14 mars 2015 kl. 14:41:35 UTC+1 skrev Ben Bacarisse: >> 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; >> } > > I do not get ? 0 : d - 48; https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Conditional_Operator The 48 is "0".charCodeAt(0) which would be have been more self-documenting. > >> 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; > > What is the -- before i1 and i2? https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Arithmetic_Operators#Decrement_(--) > I was thinking that adding to negative numbers basicly a subtranction > -7+4=4-7, mult and div go before add and subtraction. So if i > implement them and powers with a parser. Will the lack of add to > negative numbers mess up things or can i use subtraction instead? I don't follow. -- Ben.