1. 程式人生 > >大數的減法運算Java程式碼實現

大數的減法運算Java程式碼實現

public static void minus(String s1, String s2) {
        boolean flag = true;// true:有負號,false:無負號(表示結果)
        if (s1.length() > s2.length()) {// s1>s2
            flag = false;
        }
        if (s1.length() == s2.length()) {//
            for (int i = 0; i < s1.length(); i++) {
                if
(s1.charAt(i) > s2.charAt(i)) { flag = false; break; } else if (s1.charAt(i) < s2.charAt(i)) { break; } } } int[] x; int i = 0, j = 0; if (flag) {// s1<s2 j = s2.length() - s1.length(); x = new
int[s2.length()]; i = 0; while (i < j) { x[i] = Integer.parseInt(String.valueOf(s2.charAt(i))); i++; } int ii = s2.length() - 1, jj = s1.length() - 1; for (; jj >= 0; ii--, jj--) { int t1 = Integer.parseInt(String.valueOf(s2.charAt(ii))); int
t2 = Integer.parseInt(String.valueOf(s1.charAt(jj))); x[ii] = t1 - t2; } } else { j = s1.length() - s2.length(); i = 0; x = new int[s1.length()]; while (i < j) { x[i++] = Integer.parseInt(String.valueOf(s1.charAt(i))); } int ii = s1.length() - 1, jj = s2.length() - 1; for (; jj >= 0; ii--, jj--) { int t1 = Integer.parseInt(String.valueOf(s1.charAt(ii))); int t2 = Integer.parseInt(String.valueOf(s2.charAt(jj))); x[ii] = t1 - t2; } } // 處理由於不夠減產生負數的情況 // System.out.println(Arrays.toString(x)); for (int ii = x.length - 1; ii > 0; ii--) { if (x[ii] < 0) { x[ii - 1] = x[ii - 1] - 1; x[ii] += 10; } } String res = new String(); if (flag) { res += '-'; } for (i = 0; i < x.length; i++) {// 去掉計算中產生的0(最前面) if (x[i] != 0) { break; } } for (; i < x.length; i++) { res += x[i]; } System.out.println("減法結果:" + res); }