使用Stack堆栈集合大数据运算

使用Stack堆栈集合大数据运算

package com.sta.to;

import java.util.Iterator;
import java.util.Stack;

public class DaMax {

	public void jiaFa(String value1, String value2) {
	
	/**
     * 更多资料欢迎浏览凯哥学堂官网:http://kaige123.com 

    * @author 小沫
    */
		
		// 把字符串用toCharArray拆成字符
		char[] c1 = value1.toCharArray();
		char[] c2 = value2.toCharArray();

		// 申请好2个Stack集合准备把字符放进去
		Stack numvalue1 = new Stack();
		Stack numvalue2 = new Stack();
		// 进栈
		for (char c : c1) {
			numvalue1.push(c);
		}
		for (char c : c2) {
			numvalue2.push(c);
		}
		//new好一个缓存池,接收sum
		StringBuffer buffer = new StringBuffer();
		int jw = 0;//进位	
		//用常用类Math获取最长的长度
		int count = Math.max(c1.length, c2.length);
		
		//把长的拿来循环
		for (int i = 0; i < count; i++) {
			//用来存放出栈的值
			int num1;
			int num2;
			//每一次出栈的值转为int 才能进行运算
			try {
				num1 = Integer.parseInt(numvalue1.pop().toString());
			} catch (Exception e) {
				num1 = 0;//如果异常那就抛出0
			}
			try {
				num2 = Integer.parseInt(numvalue2.pop().toString());
			} catch (Exception e) {
				num2 = 0;
			}
			//把num1和num2引用的值加上jw交给sum
			int sum = num1 + num2 + jw;
			if (sum >= 10) {
				//sum大于或等于10  那就要先前一位数进1
				jw = 1;
				buffer.append(sum % 10);//把总和用取摸后的余数放进缓冲池
			} else {
				jw = 0;//不大于或等于10  jw就为0 直接把总和交给缓冲池
				buffer.append(sum);
			}
		}
		if (jw == 1) {
			//问jw还等不等于1,还等于说明最前位数需要多个1  如 99+1=100
			buffer.append(1);
		}
		buffer.reverse();// 把数值反过来
		System.out.println(buffer);
	}
}

测试类:

package com.sta.to;

import java.nio.Buffer;

public class Test {

	public static void main(String[] args) {
		
		DaMax ys = new DaMax();
		
		ys.jiaFa("10", "5");//10+5
		ys.jiaFa("15", "50");//15+50
		ys.jiaFa("999999999999999", "1");//999...+1
		ys.jiaFa("99", "1");//99+1
		ys.jiaFa("80", "80");//80+80
		ys.jiaFa("8", "7");//8+7
	}
}
原文地址:https://www.cnblogs.com/kaigexuetang/p/7164051.html