1
+ // 2021秋招-去哪儿网校招-笔试编程题
2
+ // 以字符串的形式读入两个较大的数字,编写一个函数计算它们的和,以字符串形式返回。
3
+ function add ( number1 , number2 ) {
4
+
5
+ const longArr = [ ] , shortArr = [ ] ;
6
+ if ( number1 . length > number2 . length ) {
7
+ for ( const x of number1 ) longArr . push ( x )
8
+ for ( const y of number2 ) shortArr . push ( y )
9
+ } else {
10
+ for ( const x of number1 ) shortArr . push ( x )
11
+ for ( const y of number2 ) longArr . push ( y )
12
+ }
13
+
14
+ const max = longArr . length , min = shortArr . length ;
15
+ let add10 = 0 , res = '' , num , num1 , num2 ;
16
+ for ( let i = 0 ; i < max ; i ++ ) {
17
+ if ( i < min ) {
18
+ num1 = Number ( longArr [ longArr . length - i - 1 ] ) ;
19
+ num2 = Number ( shortArr [ shortArr . length - i - 1 ] ) ;
20
+ } else {
21
+ num1 = Number ( longArr [ longArr . length - i - 1 ] ) ;
22
+ num2 = 0 ;
23
+ }
24
+ num = num1 + num2 + add10 ;
25
+ add10 = 0 ;
26
+ if ( i !== max - 1 && num >= 10 ) {
27
+ num = num - 10 ;
28
+ add10 = 1 ;
29
+ }
30
+ res = num + res ;
31
+ }
32
+ return res ;
33
+ }
34
+ console . log ( add ( '589465849568' , '669784652318' ) ) ;
35
+ console . log ( 589465849568 + 669784652318 ) ;
0 commit comments