这个大数加法算法太垃圾了,高手给减减肥吧!! 本帖最后由 qiuyedao 于 2010-10-17 06:33:15 编辑 解决方案 » 免费领取超大流量手机卡,每月29元包185G流量+100分钟通话, 中国电信官方发货 用字串作的方法都差不多,以下只是寫得精簡一點而已。public static String add(String s1, String s2) { byte[] a = s1.getBytes(); byte[] b = s2.getBytes(); byte[] c = new byte[a.length > b.length ? a.length + 1 : b.length + 1]; int next = 0; for (int i = 0; i < c.length; i++) { c[c.length - i - 1] = 48; int ia = i >= a.length ? 48 : a[a.length - i - 1]; int ib = i >= b.length ? 48 : b[b.length - i - 1]; c[c.length - i - 1] = (byte) (next + ia + ib - 48); if (c[c.length - i - 1] - 48 >= 10) { next = 1; c[c.length - i - 1] -= 10; } else { next = 0; } } String returnStr = new String(c); return returnStr.charAt(0) == '0' ? returnStr.substring(1) : returnStr.substring(0); } public static void main(String[] args) { System.out.println(add("12345678909876543211234567890", "99999999999999999999999999999")); } 有个BigInteger的类,可以直接用那个类的 知道有BigInteger类,但是人家不让用,只能自己编写了一个能用的。 Java复写了父类的方法后,怎么可以在跳出父类方法的同时,子类中该方法复写的内容也不执行..具体代码见下 Java 添加的按钮运行后不显示,调整大小后才会出来? 请教各位大侠一个问题: string[]中查找问题 有关类加载的 问题 [200分]用java程序开发一个编辑器,如何使编辑的文字内容高亮显示 怎样实现类似聊天室的自动滚屏?? HashMap中键对应的值可以重复吗 动态类的问题 怎样在AWT里显示说明标签? int转换成byte类型问题 Swing 导出csv文件
byte[] a = s1.getBytes();
byte[] b = s2.getBytes();
byte[] c = new byte[a.length > b.length ? a.length + 1 : b.length + 1];
int next = 0;
for (int i = 0; i < c.length; i++) {
c[c.length - i - 1] = 48;
int ia = i >= a.length ? 48 : a[a.length - i - 1];
int ib = i >= b.length ? 48 : b[b.length - i - 1];
c[c.length - i - 1] = (byte) (next + ia + ib - 48);
if (c[c.length - i - 1] - 48 >= 10) {
next = 1;
c[c.length - i - 1] -= 10;
} else {
next = 0;
}
}
String returnStr = new String(c);
return returnStr.charAt(0) == '0' ? returnStr.substring(1) : returnStr.substring(0);
} public static void main(String[] args) {
System.out.println(add("12345678909876543211234567890", "99999999999999999999999999999"));
}