转换分数为字符串,并插入[]的重复部分字符串、数为、部分

2023-09-11 22:45:51 作者:⒈个ん啲ぜ界

这是面试问题:

由于两个int N(分子)和D(分母),返回部分字符串。如果小数重复,然后显示重复的部分支架。

Given two int N (numerator) and D (denominator), return the fraction in string. if the fraction is repeating, then display the repeating part in bracket.

例: 输入:N = 1,D = 3 输出:0。[3]

Example: Input: N=1, D=3 output: 0.[3]

例: 输入:N = 2,D = 5 输出:0.4

Example: Input: N=2, D=5 output: 0.4

我的想法:

得到= N / D与双重价值。

get a = N/D with double value.

有关小数点后的部分,让每一位由×10 在这个过程中,如果发现重复,记录索引和插入[]最后。

for part after decimal point, get each digit by x 10 in the process, if find repeating, record the index and insert [] finally.

有关小数点前的部分,让每一位通过/ 10

for part before decimal point, get each digit by / 10

更好的想法?

感谢

推荐答案

我会避免使用像瘟疫双。由于有限precision,它不会给你正确的答案。坚持整数运算和模拟长除法,跟踪的其余部分。当您在分子用完数字(所以你打倒零),还留着余的历史,如果你看到一个余数已在历史上,它告诉你,你已经打了一个重复序列。然后,您可以构建括号内的输出部分。 (如果碰到零剩余,当然,这意味着,答案是一个终止分数。)

I would avoid using a double like the plague. Due to finite precision, it will not give you the correct answer. Stick to integer arithmetic and simulate long division, keeping track of the remainder. After you run out of digits in the numerator (so you are bringing down zeros), also keep a history of remainders and if you see a remainder that is already in the history, that tells you that you have hit a repeating sequence. You can then construct the bracketed output part. (If you hit a zero remainder, of course, that means that the answer is a terminating fraction.)