本篇内容主要讲解“不使用系统自带的BigInteger如何实现大整数相减”,感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学习“不使用系统自带的BigInteger如何实现大整数相减”吧!
第一道题目: 字符串分割,不准使用系统自带的分割函数。
public class Myspilt { public static void main(String[] args) { String source = "abcdabeefabfgeeabcfffdsfsa"; // abcdabeefabfgeeabcfffdsfsa String target = "ab"; myspilt(source, target); } public static void myspilt(String source, String target) { char[] sourceCharArray = source.toCharArray(); char[] targetCharArray = target.toCharArray(); StringBuffer stringBuffer = new StringBuffer(); List<String> result = new ArrayList<>(); for (int i = 0; i < source.length(); i++) { int j = 0; for (; j < target.length() && i + j < source.length(); j++) { if (sourceCharArray[i + j] != targetCharArray[j]) { break; } } if (j == targetCharArray.length) { if (stringBuffer.length() > 0) { result.add(stringBuffer.toString()); stringBuffer.setLength(0); } i = i + j - 1; } else { stringBuffer.append(sourceCharArray[i]); } } if (stringBuffer.length() > 0) { result.add(stringBuffer.toString()); } System.out.println("end"); } }
第二道题目: 大整数相减,不准使用系统自带的BigInteger 来计算。
class App1 { // 计算 a - b public static void main(String[] args) { String a = "454656875457421545474578457"; String b = "12454578787878454744545454578454578474516938271458457214"; mySubtract(a, b); String a1 = "1000000000000000000"; String b1 = "999999999"; mySubtract(a1, b1); } public static void mySubtract(String a, String b) { BigInteger a1 = new BigInteger(a); BigInteger b1 = new BigInteger(b); System.out.println(a1.subtract(b1).toString()); boolean altb = false; if (a.length() < b.length() || (a.length() == b.length() && a.compareTo(b) < 0)) { altb = true; String tmp = a; a = b; b = tmp; } boolean borrow = false; StringBuilder sb = new StringBuilder(a.length()); for (int i = a.length() - 1, j = b.length() - 1; i >= 0; i--, j--) { char char1 = a.charAt(i); char char2 = '0'; if (j >= 0) { char2 = b.charAt(j); } if (borrow) { char1--; } if (char1 < char2) { borrow = true; sb.append(char1 + 10 - char2); } else { borrow = false; sb.append(char1 - char2); } } String result = sb.reverse().toString(); result = result.replaceAll("^[0]+", ""); if(result.length() == 0){ result = "0" ; } if (altb) { result = "-" + result; } System.out.println(result); } }
到此,相信大家对“不使用系统自带的BigInteger如何实现大整数相减”有了更深的了解,不妨来实际操作一番吧!这里是亿速云网站,更多相关内容可以进入相关频道进行查询,关注我们,继续学习!
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。