当前位置:网站首页>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/
边栏推荐
- LeetCode 144二叉树的前序遍历、LeetCode 114二叉树展开为链表
- Edlines: a real time line segment detector with a false detection control
- idea插件备份表
- Cookie&Session
- [nine day training] content III of the problem solution of leetcode question brushing Report
- 数据库中COMMENT关键字的使用
- Appium fundamentals of automated testing - basic principles of appium
- 389. 找不同
- Addition without addition, subtraction, multiplication and division
- How to display scrollbars on the right side of the background system and how to solve the problem of double scrollbars
猜你喜欢

FCN full Convolution Network Understanding and Code Implementation (from pytorch Official Implementation)

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

Promql select time series

C语言的sem_t变量类型
![[ta - Frost Wolf May - 100 people plan] 2.3 Introduction aux fonctions communes](/img/be/325f78dee744138a865c13d2c20475.png)
[ta - Frost Wolf May - 100 people plan] 2.3 Introduction aux fonctions communes

Leetcode 31 next spread, leetcode 64 minimum path sum, leetcode 62 different paths, leetcode 78 subset, leetcode 33 search rotation sort array (modify dichotomy)
![[深度学习]激活函数(Sigmoid等)、前向传播、反向传播和梯度优化;optimizer.zero_grad(), loss.backward(), optimizer.step()的作用及原理](/img/9f/187ca83be1b88630a6c6fbfb0620ed.png)
[深度学习]激活函数(Sigmoid等)、前向传播、反向传播和梯度优化;optimizer.zero_grad(), loss.backward(), optimizer.step()的作用及原理

详解Spark运行模式(local+standalone+yarn)

Addition without addition, subtraction, multiplication and division
![[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
随机推荐
衡量两个向量相似度的方法:余弦相似度、pytorch 求余弦相似度:torch.nn.CosineSimilarity(dim=1, eps=1e-08)
Appium自动化测试基础 — APPium基本原理
复习专栏之---消息队列
ASGNet论文和代码解读2
171. Excel 表列序号
168. Excel表列名称
GCC usage, makefile summary
还在浪费脑细胞自学吗,这份面试笔记绝对是C站天花板
Learning notes for introduction to C language multithreaded programming
6. Z 字形变换
[small sample segmentation] interpretation of the paper: prior guided feature enrichment network for fee shot segmentation
Bilinear upsampling and f.upsample in pytorch_ bilinear
208. 实现 Trie (前缀树)
Valentine's Day is nothing.
idea插件备份表
166. 分数到小数
Cookie&Session
Complete knapsack problem
【TA-霜狼_may-《百人计划》】1.4 PC手机图形API介绍
Are you still wasting brain cells for self-study? This interview note is definitely the ceiling of station C