File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change 1+ /**
2+ *
3+ * @param {string } a
4+ * @param {string } b
5+ * @returns
6+ */
7+ function addBigNumber ( a , b ) {
8+ let i = a . length - 1 ;
9+ let j = b . length - 1 ;
10+ let carry = 0 ; // 进位信息
11+ // 如果用数组进行管理还复杂化了,不如直接设一个变量存储进位信息
12+ let res = "" ;
13+
14+ while ( i >= 0 || j >= 0 || carry > 0 ) {
15+ const x = i >= 0 ? a [ i ] - '0' : 0 ; // >=0 实现越界处理
16+ const y = j >= 0 ? b [ j ] - '0' : 0 ;
17+
18+ const sum = x + y + carry ;
19+ res = ( sum % 10 ) + res ;
20+ carry = Math . floor ( sum / 10 ) ;
21+
22+ i -- ;
23+ j -- ;
24+ }
25+
26+ return res ;
27+ }
28+ console . log ( addBigNumber ( '1111111111111111' , '22222222222222222222' ) )
29+
30+ function multiplyBigNumber ( num1 , num2 ) {
31+ if ( num1 === "0" || num2 === "0" ) return "0" ;
32+
33+ const m = num1 . length ;
34+ const n = num2 . length ;
35+ const res = new Array ( m + n ) . fill ( 0 ) ;
36+ // num1[i] * num2[j] 的结果会落在结果数组的 i + j 和 i + j + 1 位置
37+
38+ // O(m*n)
39+ for ( let i = m - 1 ; i >= 0 ; i -- ) {
40+ for ( let j = n - 1 ; j >= 0 ; j -- ) {
41+ const x = num1 . charCodeAt ( i ) - 48 ; // num1[i] - 48
42+ const y = num2 . charCodeAt ( j ) - 48 ;
43+
44+ const mul = x * y ;
45+ const p1 = i + j ;
46+ const p2 = i + j + 1 ;
47+
48+ const sum = mul + res [ p2 ] ;
49+ res [ p2 ] = sum % 10 ;
50+ res [ p1 ] += Math . floor ( sum / 10 ) ;
51+ }
52+ }
53+
54+ let start = 0 ;
55+ while ( start < res . length && res [ start ] === 0 ) {
56+ start ++ ;
57+ }
58+
59+ return res . slice ( start ) . join ( "" ) ;
60+ }
Original file line number Diff line number Diff line change 1+ function solve ( n ) {
2+ const ans = [ ]
3+ const cur = [ ]
4+
5+ // 求路径的话不适合回溯,面试官说错了
6+ function dfs ( step ) {
7+ if ( step < 0 ) return
8+
9+ if ( step === 0 ) {
10+ ans . push ( [ ...cur ] )
11+ return
12+ }
13+
14+ cur . push ( 1 )
15+ dfs ( step - 1 )
16+ cur . pop ( )
17+
18+ cur . push ( 2 )
19+ dfs ( step - 2 )
20+ cur . pop ( )
21+ }
22+
23+ dfs ( n )
24+ return ans
25+ }
Original file line number Diff line number Diff line change 1+ // toLocaleString 原生API
2+ function localeAPI ( num : number ) : string {
3+ return num . toLocaleString ( )
4+ }
5+ console . log ( localeAPI ( 1234567890 ) )
6+
7+
8+ function formatThousands ( num ) {
9+ const str = String ( num )
10+ const [ intPart , decimalPart ] = str . split ( '.' )
11+ // 小数处理
12+
13+ let res = ''
14+ let count = 0
15+
16+ for ( let i = intPart . length - 1 ; i >= 0 ; i -- ) {
17+ res = intPart [ i ] + res
18+ count ++
19+
20+ if ( count % 3 === 0 && i !== 0 ) {
21+ res = ',' + res
22+ }
23+ }
24+
25+ return decimalPart !== undefined ? res + '.' + decimalPart : res
26+ }
27+
28+ console . log ( formatThousands ( 1234567890 ) ) // 1,234,567,890
29+ console . log ( formatThousands ( 1234567.89 ) ) // 1,234,567.89
You can’t perform that action at this time.
0 commit comments