当前位置:网站首页>166. fractions to decimals
166. fractions to decimals
2022-07-01 03:43:00 【Sun_ Sky_ Sea】
166. Fractions to decimals
Original title link :https://leetcode.cn/problems/fraction-to-recurring-decimal/
Given two integers , Molecules representing fractions respectively numerator Denominator denominator, With Returns a decimal as a string .
If the decimal part is a circular decimal , The loop is enclosed in brackets .
If there are multiple answers , Just go back Any one .
For all given inputs , Guarantee The length of the answer string is less than 104 .
Example 1:
Input :numerator = 1, denominator = 2
Output :“0.5”
Example 2:
Input :numerator = 2, denominator = 1
Output :“2”
Example 3:
Input :numerator = 4, denominator = 333
Output :“0.(012)”
Tips :
-231 <= numerator, denominator <= 231 - 1
denominator != 0
Their thinking :
First determine whether the denominator is 0, In judging the sign , Then determine whether the decimal number is circular . Use a dictionary to determine if decimals are circular ,key Is the remainder ,value Is the quotient of the remainder divided by the divisor , That is to return the corresponding index position of the number in the string .
Code implementation :
class Solution:
def fractionToDecimal(self, numerator: int, denominator: int) -> str:
# The denominator is 0
if numerator == 0:
return "0"
ans = []
if (numerator > 0) ^ (denominator > 0):
ans.append("-")
numerator, denominator = abs(numerator), abs(denominator)
a, b = divmod(numerator, denominator)
ans.append(str(a))
# Remainder is 0, To divide or divide
if b == 0:
return "".join(ans)
# There are decimals without division , Add a decimal point
ans.append(".")
# Use a dictionary to record where decimals begin
# key Is the remainder ,value The quotient of the remainder after division corresponds to ans Position in
loc = {
b: len(ans)}
# Deal with the remainder
while b:
# The remainder is not enough for division , Expand the remainder by one digit , That's multiplied by 10
b *= 10
# a It's business. ,b Is the remainder , Did a division to update the remainder
a, b = divmod(b, denominator)
ans.append(str(a))
# If the remainder appears in the dictionary , It means that the cycle begins to repeat
# Add brackets according to the meaning of the question
if b in loc:
ans.insert(loc[b], "(")
ans.append(")")
break
# Record the new remainder, and the quotient after division corresponds to ans Position in
loc[b] = len(ans)
return "".join(ans)
reference :
https://leetcode.cn/problems/fraction-to-recurring-decimal/solution/ji-lu-yu-shu-by-powcai/
边栏推荐
猜你喜欢
![[deep learning] activation function (sigmoid, etc.), forward propagation, back propagation and gradient optimization; optimizer. zero_ grad(), loss. backward(), optimizer. Function and principle of st](/img/9f/187ca83be1b88630a6c6fbfb0620ed.png)
[deep learning] activation function (sigmoid, etc.), forward propagation, back propagation and gradient optimization; optimizer. zero_ grad(), loss. backward(), optimizer. Function and principle of st

Leetcode 128 longest continuous sequence (hash set)

IPv4和IPv6、局域网和广域网、网关、公网IP和私有IP、IP地址、子网掩码、网段、网络号、主机号、网络地址、主机地址以及ip段/数字-如192.168.0.1/24是什么意思?

Bilinear upsampling and f.upsample in pytorch_ bilinear

Ridge regression and lasso regression

Nacos

Appium automation test foundation -- supplement: c/s architecture and b/s architecture description

The method to measure the similarity of two vectors: cosine similarity, pytorch calculate cosine similarity: torch nn. CosineSimilarity(dim=1, eps=1e-08)

Download and installation configuration of cygwin

pytorch中的双线性插值上采样(Bilinear Upsampling)、F.upsample_bilinear
随机推荐
[party benefits] jsonobject to string, leave blank
[nine day training] content III of the problem solution of leetcode question brushing Report
How keil displays Chinese annotations (simple with pictures)
报错:Plug-ins declaring extensions or extension points must set the singleton directive to true
【TA-霜狼_may-《百人计划》】1.4 PC手机图形API介绍
Promql select time series
Access denied for user ‘ODBC‘@‘localhost‘ (using password: NO)
AfxMessageBox和MessageBox的用法
Valentine's Day is nothing.
ASGNet论文和代码解读2
RSN:Learning to Exploit Long-term Relational Dependencies in Knowledge Graphs
【TA-霜狼_may-《百人计划》】1.3纹理的秘密
Processing of menu buttons on the left and contents on the right of the background system page, and double scrolling appears on the background system page
Ridge regression and lasso regression
392. 判断子序列
FCN全卷积网络理解及代码实现(来自pytorch官方实现)
idea插件备份表
4. [WebGIS practice] software operation chapter - data import and processing
Research on target recognition and tracking based on 3D laser point cloud
What happens when a function is called before it is declared in C?