题目

32进制数相加

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
// fromCharCode() 可接受一个指定的 Unicode 值,然后返回一个字符串
// charCodeAt() 方法可返回指定位置的字符的 Unicode 编码。这个返回值是 0 - 65535 之间的整数。

function hexPlus36( string1, string2 ){
let currentIndex = 0;
let start = "0";
let end = "Z";
let isAdd = false; // 进位标志符
let startCharCode = start.charCodeAt();
let endCharCode = end.charCodeAt();
let sum = []; //总和
let Lenstring1 = string1.length;
let Lenstring2 = string2.length;
while( Lenstring1>currentIndex || Lenstring2>currentIndex ){
// 对两位进行预处理,屏蔽[9-a]中间的字符
let addA = startCharCode;
if( Lenstring1>currentIndex ){
let currentCharCode = string1.charCodeAt(Lenstring1-currentIndex-1);
if( currentCharCode >= startCharCode+9 ){
addA = currentCharCode - "a".charCodeAt() + startCharCode + 10;
} else {
addA = currentCharCode;
}
}
let addB = startCharCode;
if( Lenstring2>currentIndex ){
let currentCharCode = string2.charCodeAt(Lenstring2-currentIndex-1);
if( currentCharCode >= startCharCode+9 ){
addB = currentCharCode - "a".charCodeAt() + startCharCode + 10;
} else {
addB = currentCharCode;
}
}

// 进行加法
let sumCharCode = (isAdd&&1) + addA + addB - startCharCode;
if( sumCharCode >= startCharCode + 36 ){
sumCharCode -= 36;
isAdd = true;
}
// 回退屏蔽
if( parseInt(sumCharCode) > startCharCode+9 ){
sumCharCode += "a".charCodeAt() - startCharCode - 10;
}
sum.unshift( String.fromCharCode(sumCharCode) );
currentIndex++;
}
if( isAdd )
sum.unshift( String.fromCharCode(startCharCode+1) );
return sum.join("");
}

let result = hexPlus36("1","1");
console.log( result );

Comments

2020-11-18

⬆︎TOP