兩個函式式解決大數相加的方法

2021-09-13 18:41:48 字數 1943 閱讀 1253

解決大數相加的方法有很多,網上很容易搜到,下面介紹兩種,一種是在網上抄的,一種是自己想的,我將他們都用函式式的方式重寫了一遍。

這種是在網上抄的,的確非常簡潔

function add(a,b) 

return res.replace(/^0+/,'');

}

函式式重寫,重點在尾遞迴,這是在函式式程式設計中代替while的寫法。

let compose = (f, g) => (...args) => f(g(...args));

let addunit = a => b => b + a;

let mypop = a => a.pop(); // 有***

let mynumber = a => ~~a;

let remainderten = x => x % 10;

let isgreeternine = x => x > 9;

let replaceheadzero = x => x.replace(/^0+/, "");

let pandn = compose(mynumber, mypop);

let loop = (a, b, res, c) =>

let add = (a, b) => compose(replaceheadzero, loop)(a.split(""), b.split(""), "", 0);

自己想的

使用累加器實現

function add(a, b)  else 

return accumulator;

}, ).reverse().join('');

} return a.length >= b.length ? addmap(a, b) : addmap(b, a);

}

函式式重寫

let compose = (f, g) => x => f(g(x));

let myreverse = x => ;

let mysplit = x => x.split("");

let mytostring = x => x.tostring();

let mypushone = x =>

let setvalue = index => value => targetarray =>

let splitandreverse = compose(myreverse, mysplit);

let myreduce = x => y => y.reduce(fnhandleadd(splitandreverse(x)), );

let fnhandleadd = a => (accumulator, currentvalue, index) => ;

let addmap = (a, b) => compose(compose(r.join(""), myreverse), compose(myreduce(b), splitandreverse))(a);

let add = (a, b) => a.length >= b.length ? addmap(a, b) : addmap(b, a);

下面這種寫法,很不優雅

let addmap = (a, b) => compose(compose(r.join(""), myreverse), compose(myreduce(b), splitandreverse))(a);
最好compose可以實現組合任意個函式,效果如下

let addmap = (a, b) => compose(r.join(""), myreverse, myreduce(b), splitandreverse)(a);
實現思路在:

我在github

兩個多項式相加!

以下是本人用單鏈表所編寫的兩個多項式相加的程式,不知為何在turboc2.0上執行總有兩個errors,而且都是 declaration syntax error 還請業內高手指導!謝謝!include math.h include stdio.h typedef struct node polyn...

兩個多項式相加

每組有兩行,每行由若干空格隔開的整數構成,以回車標誌結束。每行第乙個數表示本行有幾項,每一項由兩個整數表示,第1個整數表示係數,第2個整數表示次數。include includetypedef struct node node struct node creatnode int coe,int ex...

兩個多項式相加 C

實現兩個多項式進行相加 不開闢空間 這要求實現進行相加,代價為兩個原煉表將被修改 分析 this other 就把other當前結點放置在this之前 this this other 求和為0就刪除,並全部前移一位,不等就刪除other中的當前結點並前移 注意 必須注意 n 作為始終指向 mhead...