Algorithm exercise-polynomial Addition

Source: Internet
Author: User

Algorithm exercise-polynomial Addition

JS Implementation of Polynomial Addition


Array.prototype.existKey = function(propVal){var i = 0;for(var i = 0;i < this.length; i++){if(this[i].k == propVal){return i;}}return -1;}function polynAdd(a,b){//1. parse out each expvar strA = a[0] == '-' ? a : '+' + a;var strB = b[0] == '-' ? b : '+' + b;var aNb = strA + strB ;console.log("aNb:"+aNb);var op = aNb[0];var s = "";var arr = new Array();for(var i = 1;i < aNb.length; i++){if(i == aNb.length-1){arr.push(op+s+aNb[i]);break;}if(aNb[i] == '+' || aNb[i]=='-'){arr.push(op + s);op = aNb[i];s="";}else{s+=aNb[i];}}//2. parse out parameter & key for each exp & save into arrvar expArr = new Array();for(var i = 0;i < arr.length; i++){var index = arr[i].indexOf('X');var key = arr[i].substr(index,arr[i].length);var val = index == 1 ? arr[i][0]+"1" : arr[i].substr(0,index);var existIndex = expArr.existKey(key);if(existIndex != -1){var r = eval(expArr[existIndex].v + val);expArr[existIndex].v = r>0 ? '+' + r : r;}else{expArr.push({k:key,v:val});}}//3. output resultvar resultStr = "";for(var i = 0;i < expArr.length;i++){var v = expArr[i].v == "+1" ? '+' : expArr[i].v == "-1" ? '-' : expArr[i].v;resultStr +=v +expArr[i].k;}if(resultStr[0] == '+'){resultStr = resultStr.replace('+','');}return resultStr;}//testconsole.log(polynAdd("8X2+3X3-9X5","-4X5+17X2-99X8-15X5"));


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.