| 13 | } |
| 14 | |
| 15 | public String subStrings(String num1, String num2) { |
| 16 | int m = num1.length(), n = num2.length(); |
| 17 | boolean neg = m < n || (m == n && num1.compareTo(num2) < 0); |
| 18 | if (neg) { |
| 19 | String t = num1; |
| 20 | num1 = num2; |
| 21 | num2 = t; |
| 22 | } |
| 23 | int i = num1.length() - 1, j = num2.length() - 1; |
| 24 | StringBuilder ans = new StringBuilder(); |
| 25 | for (int c = 0; i >= 0; --i, --j) { |
| 26 | c = (num1.charAt(i) - '0') - c - (j < 0 ? 0 : num2.charAt(j) - '0'); |
| 27 | ans.append((c + 10) % 10); |
| 28 | c = c < 0 ? 1 : 0; |
| 29 | } |
| 30 | while (ans.length() > 1 && ans.charAt(ans.length() - 1) == '0') { |
| 31 | ans.deleteCharAt(ans.length() - 1); |
| 32 | } |
| 33 | if (neg) { |
| 34 | ans.append('-'); |
| 35 | } |
| 36 | return ans.reverse().toString(); |
| 37 | } |
| 38 | } |