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.
> >
> > <SCRIPT LANGUAGE="Javascript">
> >
> > function naiveAdd(strOne,strTwo) {
> > if (strOne.length>=strTwo.length) {length=strOne.length;} else {length=strTwo.length;}
> > oneS = strOne.split("").reverse().join("");
> > twoS = strTwo.split("").reverse().join("");
>
> I would avoid this reversing operation. It's not needed since you can
> get the charCodeAt any index value you like.
>
> > out="";
> > remainder=0;
>
> Use var.
>
> > for (i=0;i<length;i++){
> > one=oneS.charAt(i);
> > two=twoS.charAt(i);
> > one=parseInt(one);
> > two=parseInt(two);
> > if (isNaN(one)) one = 0;
> > if (isNaN(two)) two = 0;
> > sum=one+two+remainder;
> > if (sum>=10) { sum=sum-10; remainder=1;} else {remainder=0;}
> > out=sum+out;
> > }
>
> There's a bit of duplication here and a bug: you forget that the carry
> (the usual name for your 'remainder') can be set at the end of the loop.
>
> > document.write("Sum = ",out,"<BR>");
> > }
> >
> > strOne="9003";
> > strTwo="13039";
> > naiveAdd(strOne,strTwo);
> >
> > </SCRIPT>
>
> String.prototype.digitValueAt = function (pos) {
> var d = this.charCodeAt(pos);
> return isNaN(d) ? 0 : d - 48;
> }
I do not get ? 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;
What is the -- before i1 and i2?
> 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.
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?
> --
> Ben.