转换分数为字符串,并插入[]的重复部分 [英] convert fraction into string and also insert [] for repeating part

查看:107
本文介绍了转换分数为字符串,并插入[]的重复部分的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是面试问题:

由于两个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.)

这篇关于转换分数为字符串,并插入[]的重复部分的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆