当前位置:网站首页>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/
边栏推荐
- Develop industrial Internet with the technical advantages of small programs
- Feature pyramid networks for object detection
- Include() of array
- AfxMessageBox和MessageBox的用法
- Pyramid Scene Parsing Network【PSPNet】论文阅读
- Home online shopping project
- MFC窗口滚动条用法
- 10、Scanner.next() 无法读取空格/indexOf -1
- RSN:Learning to Exploit Long-term Relational Dependencies in Knowledge Graphs
- Valid brackets (force deduction 20)
猜你喜欢
访问阿里云存储的图片URL实现在网页直接预览略缩图而不直接下载
Test function in pychram
pytorch训练深度学习网络设置cuda指定的GPU可见
Online public network security case nanny level tutorial [reaching out for Party welfare]
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
深度学习中的随机种子torch.manual_seed(number)、torch.cuda.manual_seed(number)
5. [WebGIS practice] software operation - service release and permission management
Pyramid scene parsing network [pspnet] thesis reading
随机推荐
Cygwin的下载和安装配置
Split(), split(), slice(), can't you tell?
深度学习中的随机种子torch.manual_seed(number)、torch.cuda.manual_seed(number)
LeetCode 31下一个排列、LeetCode 64最小路径和、LeetCode 62不同路径、LeetCode 78子集、LeetCode 33搜索旋转排序数组(修改二分法)
8. 字符串转换整数 (atoi)
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
Take you through a circuit board, from design to production (dry goods)
Research on target recognition and tracking based on 3D laser point cloud
C语言的sem_t变量类型
Appium automation test foundation -- supplement: c/s architecture and b/s architecture description
RSN:Learning to Exploit Long-term Relational Dependencies in Knowledge Graphs
Learning notes for introduction to C language multithreaded programming
Go tool cli for command line implementation
392. 判断子序列
GCC usage, makefile summary
Idea plug-in backup table
[reach out to Party welfare] developer reload system sequence
在 C 中声明函数之前调用函数会发生什么?
Home online shopping project
后台系统右边内容如何出现滚动条和解决双滚动条的问题