-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path大数相加.html
91 lines (80 loc) · 2.72 KB
/
大数相加.html
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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
<!DOCTYPE html>
<html lang="zh-en">
<head>
<meta charset="UTF-8">
<title>大数相加</title>
<style>
.input-a,
.input-b,
.input-z {
width: 100%;
height: 3em;
box-sizing: border-box;
}
input::-webkit-outer-spin-button,
input::-webkit-inner-spin-button {
-webkit-appearance: none;
}
input[type=“number”] {
-moz-appearance: textfield;
}
</style>
</head>
<body>
<p>输入big数字的时候不要用键盘↑↓进行加减,BigInt将会更适合,这里同样无法计算负值</p>
<input type="number" class='input-a'> +
<input type="number" class='input-b'> =
<input type="text" class='input-z' disabled>
<input type="button" value="清除">
<script>
window.addEventListener('DOMContentLoaded', function() {
//获取按钮,添加点击事件,此处实时计算结果,考虑到性能可以做防抖,或者放到按钮的事件监听里
const sum = function(delay = 2000) {
let timer;
return () => {
timer && clearTimeout(timer);
timer = setTimeout(() => {
// 从数字输入框提取数组
var a = document.querySelector('.input-a').value;
var b = document.querySelector('.input-b').value;
// 得到输出对象
var z = document.querySelector('.input-z');
//计算和并输出
z.value = strAdd(a, b);
},delay)
}
}
document.addEventListener('keyup', sum(1000))
// 点击清除时,清除所有输入
document.querySelector('input[value="清除"]').addEventListener('click', function() {
document.querySelector('.input-a').value = '';
document.querySelector('.input-b').value = '';
document.querySelector('.input-z').value = '';
})
//一位加法函数,a和b是加数,c是进位,参数都要为一位数字整数
function add(a, b, c) {
let add = a + b + c;
//返回当前个位结果 和 进位
return [add % 10, Math.floor(add / 10)];
}
//数字字符串数组的加法
function strAdd(a, b) {
// 将长度更长的字符串放进a, 短的放进b,补充0,转换成同等长度的数字数组
[a, b] = a.length > b.length ? [a, b] : [b, a];
a = a.split('').map(v => parseInt(v));
b = b.padStart(a.length, 0).split('').map(v => parseInt(v));
//定义返回数组,每次加运算的个位,进位
const result = [];
let one, carry = 0;
while (a.length) {
[one, carry] = add( a.pop(), b.pop(), carry )
//每次得到的数字添加到头部
result.unshift(one);
}
if( carry != 0) result.unshift(carry);
return result.join('')
}
})
</script>
</body>
</html>