加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

华为机试题--- 大数相加 异常处理

发布时间:2020-12-14 03:41:42 所属栏目:大数据 来源:网络整理
导读:一、问题描述; 要求实现方法public String addTwoBigNumber(String s1,string s2) ?大数相加,注意处理异常 二、算法 /** * Checks whether numberStr contains only number * @param number * @return */public boolean isNumber(String number) {boolean

一、问题描述;

要求实现方法public String addTwoBigNumber(String s1,string s2)
?大数相加,注意处理异常

二、算法

	/**
	 * Checks whether numberStr contains only number
	 * @param number
	 * @return
	 */
	public boolean isNumber(String number) {
		boolean flag = false;
		Pattern pattern = Pattern.compile("[0-9]*$");
		Matcher isNum = pattern.matcher(number);
		if (isNum.matches()) {
			flag = true;
		}
		return flag;
	}

	/**
	 * implements function of adding two big number.
	 * @param s1
	 * @param s2
	 * @return
	 */
	public String addTwoBigNumber(String s1,String s2) {
		String result = null;
		if (isNumber(s1) && isNumber(s2)) {
			try {
				BigInteger n1 = new BigInteger(s1);
				BigInteger n2 = new BigInteger(s2);
				result = String.valueOf(n1.add(n2));
			} catch (Exception e) {
				e.printStackTrace();
			}
			
		}
		return result;
	}

三、测试方法

package com.albertshao.csi.interview;

import java.math.BigInteger;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 
 * @author albertshao
 * 
 */
public class Main7 {

	public static void main(String[] args) {
		Main7 m = new Main7();
		System.out.println(m.addTwoBigNumber("123456789","987654321"));
	}

	/**
	 * Checks whether numberStr contains only number
	 * @param number
	 * @return
	 */
	public boolean isNumber(String number) {
		boolean flag = false;
		Pattern pattern = Pattern.compile("[0-9]*$");
		Matcher isNum = pattern.matcher(number);
		if (isNum.matches()) {
			flag = true;
		}
		return flag;
	}

	/**
	 * implements function of adding two big number.
	 * @param s1
	 * @param s2
	 * @return
	 */
	public String addTwoBigNumber(String s1,String s2) {
		String result = null;
		if (isNumber(s1) && isNumber(s2)) {
			try {
				BigInteger n1 = new BigInteger(s1);
				BigInteger n2 = new BigInteger(s2);
				result = String.valueOf(n1.add(n2));
			} catch (Exception e) {
				e.printStackTrace();
			}
			
		}
		return result;
	}

}

结果:

2222211110

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读