2015年11月15日星期日

bigFloatAdd

稍微聊了下问了big float加法,中间有个compile error找了半天,找到以后有个小bug,改了下,大叔自己让我弄几个test case,测了下都过了,他自己测了下也没问题,然后就完了。又聊了一会,他说他希望new grad来了三个礼拜之内能ship feature。
解法:就是把一个float分成两部分,point之前的跟point之后的,然后用类似big int加法的做法做,先处理point之后的部分,然后处理之前的那部分,注意进位就行。

import java.util.Random;

public class Solution {

public String bigFloatAdd(String f1, String f2) {
String[] part1 = split(f1);
String[] part2 = split(f2);

StringBuilder floatSum = new StringBuilder();
int carry = addFloat(part1[1], part2[1], floatSum);
String integerSum = addInteger(part1[0], part2[0], carry);
return integerSum + "." + floatSum.reverse().toString();
}

private String[] split(String f1) {
int p1 = f1.indexOf(".");
String int1 = "";
String float1 = "";
if (p1 != -1) {
int1 = f1.substring(0, p1);
float1 = f1.substring(p1 + 1);
} else {
int1 = f1;
float1 = "";
}
return new String[]{int1, float1};
}

private int addFloat(String s1, String s2, StringBuilder sb) {
int len = Math.max(s1.length(), s2.length()) - 1;
int carry = 0;
while (len >= 0) {
int val = carry;
val += len < s1.length() ? s1.charAt(len) - '0' : 0;
val += len < s2.length() ? s2.charAt(len) - '0' : 0;
len--;
carry = val / 10;
sb.append(val % 10);
}
return carry;
}

private String addInteger(String s1, String s2, int carry) {
if (s1.isEmpty()) {
return s2;
}
if (s2.isEmpty()) {
return s1;
}
int i1 = s1.length() - 1;
int i2 = s2.length() - 1;
StringBuilder sb = new StringBuilder();
while (i1 >= 0 || i2 >= 0 || carry != 0) {
int val = carry;
val += i1 >= 0 ? s1.charAt(i1) - '0' : 0;
val += i2 >= 0 ? s2.charAt(i2) - '0' : 0;
carry = val / 10;
sb.append(val % 10);
i1--;
i2--;
}
return sb.reverse().toString();
}


public static void main(String args[]) {
Solution s = new Solution();
double d1 = 2.93;
double d2 = 107.08;
double sum = d1 + d2;
String strSum = s.bigFloatAdd(Double.toString(d1), Double.toString(d2));
System.out.println(d1 + "+" + d2 + "=" + sum + " == " + strSum);
}
}

没有评论:

发表评论