2015年11月14日星期六

bigint subtract

bigint subtract

import java.util.Random;


public class Solution {

public String sub(String str1, String str2) {
if (str1.length() < str2.length() || (str1.length() == str2.length() && str1.compareTo(str2) < 0)) {
return "-" + sub(str2, str1);
}
StringBuilder sb = new StringBuilder();
int i1 = str1.length() - 1;
int i2 = str2.length() - 1;
int carry = 0;
while (i1 >= 0 || i2 >= 0) {
int val = -carry;
val += i1 >= 0 ? (str1.charAt(i1) - '0') : 0;
val -= i2 >= 0 ? (str2.charAt(i2) - '0') : 0;
if (val < 0) {
carry = 1;
val += 10;
} else {
carry = 0;
}
sb.append(val);
i1--;
i2--;
}
return sb.reverse().toString();
}

public static void main(String args[]) {
Solution s = new Solution();
Random r = new Random();
int n1 = r.nextInt(100000000);
int n2 = r.nextInt(100000000);
String n3 = s.sub(Integer.toString(n1), Integer.toString(n2));
System.out.println((n1 + "-" + n2) + "=" + (n1 - n2) + "=" + Integer.parseInt(n3));
}
}

没有评论:

发表评论