B*******1 发帖数: 2454 | 1 Given Numerator and Denominator. After division you might get a recurring
decimal points float as the answer. You need to identify the recurring part?
For example 23.34563456 ...
return 3456
完全没有idea,请大牛们指教。 | d********y 发帖数: 2114 | 2 小学的时候笔算,当出现相同的余数就开始循环了。
用hash记录小数点后面每一位的余数? | f*******t 发帖数: 7549 | 3 我觉得可以把余数放进set
先取余数,然后不断乘以10再取余
如果发现重复的余数,从它开始不断取商放进结果中,直到余数再次重复,所得的就是循环的数字 | k****n 发帖数: 369 | 4 do it directly as you do by hand?
int division(int numerator, int denominator) {
HashMap remainders = new HashMap();
StringBuffer sb = new StringBuffer();
sb.append(numerator / denominator).append(".");
return helper(numerator % denominator, denominator, remainders, sb);
}
int helper(int n, int d, HashMap remainders, StringBuffer
result) {
if (n == 0) return 0; // non-recurring
if (remainders.containsKey(n)) {
return result.toString().substring(remainders.get(n).length());
}
remainders.put(n, result.toString());
int r = 10 * n % d;
return helper(r, d, remainders, result.append(10*n / d));
}
part?
【在 B*******1 的大作中提到】 : Given Numerator and Denominator. After division you might get a recurring : decimal points float as the answer. You need to identify the recurring part? : For example 23.34563456 ... : return 3456 : 完全没有idea,请大牛们指教。
| k****n 发帖数: 369 | | S**I 发帖数: 15689 | 6 OK, I see
【在 k****n 的大作中提到】 : 说的是记录余数,不是除的结果
| d*******d 发帖数: 2050 | 7 string find_circle(int x, int y){
typedef unordered_set ISET;
ISET iset;
int i = x/y;
x = x-i*y;
string res = "";
while(x>0){
x = x*10;
pair ret = iset.insert(x);
if( ret.second == false)
break;
i = x/y;
x = x - i*y;
char c = '0' + i;
res += c;
}
return res;
} | S**I 发帖数: 15689 | 8 I think your code needs a small modification: there could be leading 0's in
the return string and they should be removed.
【在 k****n 的大作中提到】 : do it directly as you do by hand? : int division(int numerator, int denominator) { : HashMap remainders = new HashMap(); : StringBuffer sb = new StringBuffer(); : sb.append(numerator / denominator).append("."); : return helper(numerator % denominator, denominator, remainders, sb); : } : int helper(int n, int d, HashMap remainders, StringBuffer : result) { : if (n == 0) return 0; // non-recurring
| k****n 发帖数: 369 | 9 I think I have removed them...
But I haven't checked my code, maybe you are right, thanks...
in
【在 S**I 的大作中提到】 : I think your code needs a small modification: there could be leading 0's in : the return string and they should be removed.
|
|