循环小数 面试题_如何解决关于重复小数的典型面试问题

循环小数 面试题

介绍 (Introduction)

In this article, I will walk you through how to solve a typical software development interview question: Repeating Decimals.

在本文中,我将引导您逐步解决典型的软件开发面试问题:重复小数。

In order to solve this example, I decided to use Python (all the code is available here). If you want, feel free to try to solve this same exercise using any other programming language of your choice.

为了解决此示例,我决定使用Python(所有代码都在此处 )。 如果需要,请尝试使用您选择的任何其他编程语言尝试解决相同的问题。

问题 (The Problem)

Create a function able to take two numbers (the numerator and denominator of a fraction) that returns the results of the fraction in decimal form, enclosing in parenthesis any repeating decimal.
创建一个能够接受两个数字(分数的分子和分母)的函数,该函数以小数形式返回分数的结果,并将任何重复的十进制括在括号中。
Examples:
1) 1/3 = 0.(3)
2) 1/4 = 0.25
3) 1/5 = 0.2
4) 1/6 = 0.1(6)
5) 1/7 = 0.(142857)
6) 1/8 = 0.125

I will now walk you through a simple implementation to solve this problem. If you are able to create a more time and memory efficient solution, feel free to share it in the comment section below.

现在,我将引导您完成一个简单的实现以解决此问题。 如果您能够创建更节省时间和内存的解决方案,请随时在下面的评论部分中共享它。

解决方案 (The Solution)

Let's start by creating a function (repeating_dec_sol) and handling some simple exceptions:

让我们开始创建一个函数( repeating_dec_sol )并处理一些简单的异常:

  1. If the numerator is zero, return zero.

    如果分子为零,则返回零。
  2. If the denominator is zero, return Undefined (same if both numerator and denominator are equal to zero).

    如果分母为零,则返回未定义(如果分子和分母都等于零,则相同)。
  3. If the remainder is zero, (the numerator is divisible by the denominator) return directly the result of the division.

    如果余数为零,(分子可被分母整除)直接返回除法结果。
  4. If the numerator or denominator return a negative number when divided, add a minus sign at the beginning of the returned result (this will be done at the end of the code).

    如果除法时分子或分母返回负数,请在返回结果的开头添加负号(这将在代码末尾完成)。
def repeating_dec_sol(numerator, denominator):
    negative = False
    if denominator == 0:
        return 'Undefined'
    if numerator == 0:
        return '0'
    if numerator*denominator < 0:
        negative = True
    if numerator % denominator == 0:
        return str(numerator/denominator)
    
    num = abs(numerator)
    den = abs(denominator)

Now, we can simply store our output for all the digits before the decimal point by concatenating the quotient of the numerator and denominator to a string called result (which will be used later on to store the entire result of the operation).

现在,我们可以简单地将分子和分母的商连接到一个名为result的字符串中来存储小数点前所有数字的输出(稍后将用于存储操作的整个结果)。

result = ""
    result += str(num // den)
    result += "."

In order to handle the part after the decimal point, we will now start keeping track of every new numerator and quotient (quantity produced by the division of the two numbers) after the decimal point.

为了处理小数点后的部分,我们现在开始跟踪小数点后的每个新分子和商(由两个数字的和产生的数量)。

As we can see from the picture below (Figure 1), every-time there is a repeating decimal, same values of the new numerators and the quotients will be repeated multiple times.

从下图(图1)可以看出,每次都有一个重复的小数,新分子的相同值和商将重复多次。

In order to model this behaviour in Python, we can start by creating an empty list (quotient _num) which we are going to update with all the new numerators and quotients registered after the decimal point (using a list inside a list).

为了在Python中为这种行为建模,我们可以先创建一个空列表( 商_num ),然后使用小数点后注册的所有新分子和商(使用列表中的列表)进行更新。

Every time we are going to append a list containing a new numerator and quotient, we are going to check if are present in any other list the same combination of new numerator and quotient and if that's the case we will then break the execution (this flags us that we have reached a repeating decimal).

每次我们要追加一个包含新分子和商的列表时,我们都会检查是否存在其他列表中的新分子和商的相同组合,如果是这种情况,我们将中断执行(此标志我们已经达到了重复的小数)。

quotient_num = []
    while num:
    	# In case the remainder is equal to zero, there are no repeating
        # decimals. Therefore, we don't need to add any parenthesis and we can
        # break the while loop and return the result.
        remainder = num % den
        if remainder == 0:
            for i in quotient_num:
                result += str(i[-1])
            break
        num = remainder*10
        quotient = num // den

		# If the new numerator and quotient are not already in the list, we
        # append them to the list.
        if [num, quotient] not in quotient_num:
            quotient_num.append([num, quotient])
        # If the new numerator and quotient are instead already in the list, we 
        # break the execution and we prepare to return the final result.
        # We take track of the index position, in order to add the parenthesis 
        # at the output in the right place.
        elif [num, quotient] in quotient_num:
            index = quotient_num.index([num, quotient])
            for i in quotient_num[:index]:
                result += str(i[-1])
            result += "("
            for i in quotient_num[index:]:
                result += str(i[-1])
            result += ")"
            break

Finally, we can add the following code to handle the exception in case either the input numerator or denominator are negative numbers.

最后,如果输入分子或分母为负数,我们可以添加以下代码来处理异常。

if negative:
            result = "-" + result

    return result

If we now test our function we will get the following result:

如果现在测试功能,我们将得到以下结果:

NUM, DEN = 1, 6
print("The result of the fraction", NUM, "/", DEN, "is equal to: ",
       repeating_dec_sol(NUM, DEN))

# Output 
# The result of the fraction 1 / 6 is equal to:  0.1(6)

结论 (Conclusion)

I hope you enjoyed this article. If you have any questions, feel free to leave a comment below. If you are looking also for a video explanation on how to solve this type of problem, this video by PyLenin is a great place to start.

希望您喜欢这篇文章。 如有任何疑问,请在下面发表评论。 如果您还在寻找有关如何解决此类问题的视频说明,那么PyLenin的 视频就是一个不错的起点。

联络资料 (Contact info)

If you want to keep updated with my latest articles and projects, follow me and subscribe to my mailing list. These are some of my contacts details:

如果您想更新我的最新文章和项目,请关注我并订阅我的邮件列表 。 这些是我的一些联系方式:

参考书目 (Bibliography)

[1] 33 1 3 Percent As A Fraction Math Image Titled Change A Common Fraction Into A Decimal Step 8 Mathpapa Slope - lugezi.com. Accessed at: http://novine.club/wp-content/uploads//2018/09/33-1-3-percent-as-a-fraction-math-image-titled-change-a-common-fraction-into-a-decimal-step-8-mathpapa-slope.jpg

[1] 33 1 3以分数表示的数学图像以标题为“将常用分数转换为小数位数”的步骤8 Mathpapa斜率-lugezi.com。 访问网址: http : //novine.club/wp-content/uploads//2018/09/33-1-3-percent-as-a-fraction-math-image-titled-change-a-common-fraction-进入小数步8-mathpapa-slope.jpg

翻译自: https://www.freecodecamp.org/news/interview-questions/

循环小数 面试题

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值