Are we allowed in this problem to keep the intermediary result in a StringBuilder? Or a list of digits?
For example: 0.3/0.7
We see 0.3<0.7 => we have a 0 and multiply by 10
3/0.7 => we have a 4 and 0.2/0.7 and multiply by 10
2/0.7=> we have a 2 and so on…
Question is, can we keep these digits in a list? A StringBuilder? I don’t see a way in which we can directly assemble a double value incrementally (adding decimals to it).
(Java) Problem 12.6 Version
I think you can keep these digits in a list or anything you want like StringBuilder. However, the problem is that it would be hard to use a StringBuilder to represent the trailing digits of a floating point number.
I tried to use a StringBuilder from which the final result is assembled using a parseDouble.
How I knew when to stop the computation? After each iteration i multiplied the tolerance with 10 until it got bigger than 1.
The problem is that it might not stop the computation when you treat the number as string. So that is the reason we don’t use string here.
I didn’t use strings in deciding that. I stopped the computation when the modified tolerance was bigger or equal to 1.
StringBuilder sb=new StringBuilder();
While(compare(tolerance,1)<0){
Int val=0;
While(compare(x,y)>=0){
X-=y;
Val++;
}
Sb.append(val);
If(!reachedDecimals){
Sb.append(".");
ReachedDecimals=true;
}
Tolerance*=10;
X*=10;
}
Return Double.valueOf(sb.toString());
}
The code is not formatted so it is hard to tell it is working or not. However, I think you might want to try that yourself with with some debugging tool to verify that. As I told before, please feel free to use the program on our website as golden to verify your program.