HDOJ-ACM1002(JAVA实现 自定义大数处理类MBigInteger)
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了HDOJ-ACM1002(JAVA实现 自定义大数处理类MBigInteger)相关的知识,希望对你有一定的参考价值。
转载声明:原文转自http://www.cnblogs.com/xiezie/p/5502809.html
JAVA语言实现:
import java.util.*; import java.io.*; public class Main{ public static void main(String[] arg){ Main m = new Main(); Scanner scan = new Scanner(new BufferedInputStream(System.in)); int n = scan.nextInt(); int l = n; while(n--!=0){ MBigInteger integer = m.new MBigInteger(scan.next()); MBigInteger integer2 = m.new MBigInteger(scan.next()); System.out.println("Case " + (l-n) + ":"); System.out.println(integer + " + " + integer2 + " = " + integer.add(integer2)); if(n!=0){ System.out.println(); } } scan.close(); } class MBigInteger{ private MBigInteger(){}; private String s; public MBigInteger(String s){ this.setS(s); } public MBigInteger add(MBigInteger integer){//只处理正整数 char[] ch1 = getS().toCharArray(); char[] ch2 = integer.getS().toCharArray(); int len = ch1.length; int len2 = ch2.length; int n = len; char[] resultChars; if(len<len2){ n = len2; } resultChars = new char[ n ]; boolean overTen = false; int ans; while(len!=0&&len2!= 0){ int o = 0; if(overTen){ o++; } ans = getIntValueAt(ch1, len-1) + getIntValueAt(ch2, len2-1) + o; if(ans > 9){ overTen = true; }else{ overTen = false; } resultChars[--n] = (char) (ans%10 + ‘0‘); len -- ; len2 -- ; } while(len--!=0){ int o = 0; if(overTen){ o++; } ans = getIntValueAt(ch1, len) + o; if(ans > 9){ overTen = true; }else{ overTen = false; } resultChars[--n] = (char) (ans%10 + ‘0‘); } while(len2--!=0){ int o = 0 ; if(overTen){ o++; } ans = getIntValueAt(ch2, len2) + o; if(ans > 9){ overTen = true; }else{ overTen = false; } resultChars[--n] = (char) (ans%10 + ‘0‘); } if(overTen){ setS("1".concat(String.valueOf(resultChars))); }else{ setS(String.valueOf(resultChars)); } return this; } @Override public String toString() { return this.getS(); } public String getS() { return s; } public void setS(String s) { this.s = s; } public int getIntValueAt(char[] c,int i){ return c[i]-‘0‘; } } }
以上是关于HDOJ-ACM1002(JAVA实现 自定义大数处理类MBigInteger)的主要内容,如果未能解决你的问题,请参考以下文章
HDOJ-ACM1061(JAVA) Rightmost Digit