当前位置:网站首页>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/
边栏推荐
- 衡量两个向量相似度的方法:余弦相似度、pytorch 求余弦相似度:torch.nn.CosineSimilarity(dim=1, eps=1e-08)
- bootsrap中的栅格系统
- 242. 有效的字母异位词
- Future of NTF and trends in 2022
- 小程序容器技术与物联网IoT的结合点
- 【快捷键】
- 6. Z 字形变换
- [reach out to Party welfare] developer reload system sequence
- Its appearance makes competitors tremble. Interpretation of Sony vision-s 02 products
- 168. Excel表列名称
猜你喜欢

Feature Pyramid Networks for Object Detection论文理解

Feign remote call and getaway gateway

Avalanche problem and the use of sentinel

Nacos

Feature pyramid networks for object detection

pytorch训练深度学习网络设置cuda指定的GPU可见

Binary tree god level traversal: Morris traversal
![5. [WebGIS practice] software operation - service release and permission management](/img/5d/070e207bd96e60ba1846d644d4fb54.png)
5. [WebGIS practice] software operation - service release and permission management

C语言的sem_t变量类型

衡量两个向量相似度的方法:余弦相似度、pytorch 求余弦相似度:torch.nn.CosineSimilarity(dim=1, eps=1e-08)
随机推荐
pytorch中的双线性插值上采样(Bilinear Upsampling)、F.upsample_bilinear
Use of comment keyword in database
C语言的sem_t变量类型
Its appearance makes competitors tremble. Interpretation of Sony vision-s 02 products
后台系统右边内容如何出现滚动条和解决双滚动条的问题
Golang multi graph generation gif
【EI会议】2022年第三届纳米材料与纳米技术国际会议(NanoMT 2022)
How to display scrollbars on the right side of the background system and how to solve the problem of double scrollbars
Ouc2021 autumn - Software Engineering - end of term (recall version)
[deep learning] activation function (sigmoid, etc.), forward propagation, back propagation and gradient optimization; optimizer. zero_ grad(), loss. backward(), optimizer. Function and principle of st
访问阿里云存储的图片URL实现在网页直接预览略缩图而不直接下载
Error: plug ins declaring extensions or extension points must set the singleton directive to true
171. Excel 表列序号
Feign remote call and getaway gateway
在线公网安备案保姆级教程【伸手党福利】
The shell script uses two bars to receive external parameters
The combination of applet container technology and IOT
FCN全卷积网络理解及代码实现(来自pytorch官方实现)
在 C 中声明函数之前调用函数会发生什么?
8. 字符串转换整数 (atoi)