js实现大数加法

发布于 2018-05-19  970 次阅读


测试网址

html部分



	
		
		
		
	
	
		

num1

num2

ans

js部分

window.onload = function(){
	var bun = document.getElementById('bun1');
	var num1 = document.getElementById('tex1');
	var num2 = document.getElementById('tex2');
	var num3 = document.getElementById('tex3');
	num3.readOnly = true;
	
	function swap(){
		var tmp = num1.value;
		num1.value = num2.value;
		num2.value = tmp;
	}
	
	bun.onclick = function(){
		if(num2.value.length > num1.value.length)
			swap();
		if(num2.value > num1.value && num2.value.length == num1.value.length)
			swap();
		var ans = new Array(num1.value.length + 1);
		ans.fill(0);
		var zero = "";
		for(var i = num2.value.length; i < num1.value.length; i++)
			zero += '0';
		num2.value = zero + num2.value;
		var cnt = 0;
		for(var i = num1.value.length - 1; i >= 0; i--){
			ans[cnt] += parseInt(num1.value[i]) + parseInt(num2.value[i]);
			while(ans[cnt] >= 10){
				ans[cnt] -= 10;
				ans[cnt+1]++;
			}
			cnt++;
		}
		var i;
		var res="";
		for(i = cnt; i >= 0; i--)
			if(ans[i] != 0)
				break;
		if(i == -1)
			res += '0';
		for(; i >= 0; i--)
			res += ans[i];
		num3.value = res;
	}
}