您好,登錄后才能下訂單哦!
本篇內容主要講解“不使用系統自帶的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進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。