166. Fraction to Recurring Decimal (M)

CSP-J 复试考点 可以用来训练思维,对于学习时间短的同学,动态规划可以帮助你迅速进入编程状态,也有助于帮你发现题目背后可能隐藏的更简便的算法。动态规划、贪心都是和子问题相关的,动态规划的基本思想是将一个大的问题划分成子问题,接着分别求解,而且能够将一些重复的计算记忆化,大大提高效率。难度加大,会涉及到二分、动态规划之类的算法,容易遗漏考虑点,不易得全分,考试的时候要注意全面性。一般是压轴题,算法不明显,剪枝的搜索、动态规划、状压 DP、树形 DP 、树、图等。枚举算法是指,列举出所有可能的取值,从中找出最优解。 阅读详情

Fraction to Recurring Decimal (M)

Given two integers representing the numerator and denominator of a fraction, return the fraction in string format.

If the fractional part is repeating, enclose the repeating part in parentheses.

Example 1:

Input: numerator = 1, denominator = 2
Output: "0.5"

Example 2:

Input: numerator = 2, denominator = 1
Output: "2"

Example 3:

Input: numerator = 2, denominator = 3
Output: "0.(6)"

题意

计算一个分数表示的有理数的小数形式,若为无限循环小数,则将循环部分用括号标记。

思路

直接按照小学除法步骤进行模拟,判断出现循环的依据是计算过程中有余数出现了两次,利用Hash进行标记。


代码实现

class Solution {
    public String fractionToDecimal(int numerator, int denominator) {
        Map<Long, Integer> map = new HashMap<>();	// key为余数值,value为对应的小数位
        StringBuilder sb = new StringBuilder();
        
        // 先将分子分母全部转化为正数,并记录符号信息
        // 因为最小负int取绝对值后会溢出,所以全用long来计算
        boolean negative = numerator < 0 && denominator > 0 || numerator > 0 && denominator < 0;
        long dividend = Math.abs((long) numerator), divisor = Math.abs((long) denominator);
        long remainder = dividend % divisor, quotient = dividend / divisor;

        sb.append(quotient);			// 将整数部分存入
        // 仍有余数,说明存在小数部分
        if (remainder != 0) {
            sb.append(".");
            // 余数最终为0,说明是有限小数,不为0则需要找到无限循环小数的循环部分
            while (remainder != 0) {
                if (!map.containsKey(remainder)) {
                    map.put(remainder, sb.length());
                    quotient = remainder * 10 / divisor;
                    remainder = remainder * 10 % divisor;
                    sb.append(quotient);
                } else {
                    sb.insert(map.get(remainder), "(");
                    sb.append(')');
                    break;
                }
            }
        }
        
        return (negative ? "-" : "") + sb.toString();
    }
}
【Claude】Invalid model / Opus not available 错误:模型不可用的原因 bug报错已解决 使用 Claude API 时,指定错误或不可用的模型 ID 会收到 Invalid model 错误。本文从模型命名规则出发,给出模型降级链与动态选择方案。 阅读详情

相关推荐

Claude Code vs Codex

Claude Code 提供了一个生产就绪(production-ready)的实现,包含良好的错误处理、优雅的关闭逻辑、详细注释和文档,以及内置测试。Claude Code 输出了一个可运行的 Next.js + TypeScript 前端,但错过了一些设计里的黄色主题元素;Codex 则生成自己的版本,没有导出设计中的图片,也没严格遵照设计主题。Codex 完成同样功能,但更简洁直接,文档和注释少一些但功能达标。任务都用同样的提示,使用 TypeScript 实现,并在一天内完成。

weixin_49869937的博客 2387

【leetcode】166. Fraction to Recurring Decimal

一、题目描述 Given two integers representing the numerator and denominator of a fraction, return the fraction in string format. If the fractional part is repeating, enclose the repeating part in par

小拳头的博客 516

大疆航线文件解析指南:5分钟搞懂KMZ里的template.kml和waylines.wpml区别

本文深入解析大疆无人机航线文件KMZ中template.kml与waylines.wpml的核心区别。template.kml是定义任务框架和全局参数的可编辑模板,而waylines.wpml是包含精确执行指令的最终文件。理解两者差异对于高效规划航线、批量生成任务及进行二次开发至关重要。

sun99的博客 866

Leetcode 166. Fraction to Recurring Decimal

Given two integers representing the numerator and denominator of a fraction, return the fraction in string format. If the fractional part is repeating, enclose the repeating part in parentheses. Exa...

salmonwilliam的博客 386

Abaqus边界条件设置避坑指南:为什么你的实体单元转动自由度总是不生效?

本文深入解析了Abaqus中实体单元转动自由度设置失效的根本原因。从力学原理与有限元节点自由度的本质区别出发,阐明了实体单元仅具有平动自由度,直接约束其转动自由度是无效操作。文章提供了对称边界条件的正确设置方法,并给出了使用耦合约束等高级方案来模拟真实抗转动约束的实战指南,帮助用户避免常见建模陷阱。

weixin_29290379的博客 621

UE5.1实战:从零到打包,手把手教你用UMG和蓝图搭建智慧城市数字孪生界面

本文详细介绍了如何使用UE5.1的UMG和蓝图系统从零开始构建智慧城市数字孪生界面。通过环境准备、UMG界面设计、蓝图功能实现、数据绑定到最终打包发布的全流程指导,帮助开发者掌握数字孪生技术的核心应用,提升智慧城市可视化开发效率。

weixin_30251829的博客 619

leetcode[166]Fraction to Recurring Decimal

---恢复内容开始--- Given two integers representing the numerator and denominator of a fraction, return the fraction in string format. If the fractional part is repeating, enclose the repeating part in par...

weixin_30823001的博客 79

基于龙虾Claw的会议纪要自动提取与重点内容总结办公场景实践

本文介绍如何使用龙虾Claw构建会议纪要自动提取与重点内容总结系统,实现会议内容的智能处理。

一键难忘的博客 253

Leetcode 166 Fraction to Recurring Decimal 分数化小数

给出两个整数,一个分子一个分母,将该分数转化为小数并返回字符串。如果小数部分有循环,将其规约在括号内。

(ง •̀_•́)ง 1350

多模态论文笔记——VQ-VAE和VQ-VAE-2

本文详细介绍VQ-VAE和VQ-VAE-2的原理和训练过程,为后面的dVAE在DALLE中的使用打下坚实的基础。

haopinglianlian的博客 3299

2026年最值得学习的十大 SAP 开发技术

在这辞旧迎新之际,我想和大家聊聊我心中的2026年我仍然愿意持续投入时间去学习的一些 SAP 开发技术。因为笔者水平和视野局限,加上这份清单有笔者主观兴趣爱好在内,可能大家对清单上罗列的技术有不同意见,欢迎大家在评论区发表自己的见解。下面是笔者列出的十个技术方向,排名不分先后。因为精力有限,2026年我很可能只会选择其中一两个自己最感兴趣的方向去深耕。每项技术后面都提供了链接,方便大家看完就开始学习。

2007 年 ~ 2025 年,深耕 SAP 技术 18 年 1519

LeetCode-166 Fraction to Recurring Decimal

题目描述 Given two integers representing the numerator and denominator of a fraction, return the fraction in string format. If the fractional part is repeating, enclose the repeating part in parentheses...

weixin_30268071的博客 117

vue3中使用antv-S2表格(基础功能版)

表格的数值默认会渲染排序 icon, 可以配置 showDefaultHeaderActionIcon关闭。当配置为对象时,always 控制是否在子维度不足 2 个时始终展示小计,默认不展示。首先创建一个vue3+vite+ts项目,可以查看下面相关文章,只看第一条即可。可以调整行宽、列宽、列排序、单个单元格详情展示、选中某列、某行等基本功能。可以通过上面设置的SUM函数自动计算出数值,也可以自定义累加函数。配置自定义方法优先级大于配置聚合方式,即配置。1、在项目中安装(npm/pnpm都可以)

蜗牛~~ 2210

LeetCode -166. Fraction to Recurring Decimal 计算除法

LeetCode - 166. Fraction to Recurring Decimal Given two integers representing the numerator and denominator of a fraction, return the fraction in string format. If the fractional part is repeating, e...

Bob__yuan的博客 280

pscad IEEE标准系统搭建说明

pscad IEEE标准系统搭建说明,包含典型的IEEE 9节点、14节点、30节点、39节点和118节点系统。内含标准测试系统的原始数据和潮流结果。

RU DOS版、EFI版32bit/64bit BIOS常用工具

DOS版、EFI版的RU工具,可用来查看IO、MEM、PCI、SMBIOS等资源。亲测在EFI SHELL下可用。

LeetCode 166:Fraction to Recurring Decimal

Given two integers representing the numerator and denominator of a fraction, return the fraction in string format. If the fractional part is repeating, enclose the repeating part in parentheses. Examp...

qq_34314736的博客 163

廖雪峰Python教程[完整版]

廖雪峰的python教程整理的,已经排好版了,而且还是完整的,适合小白

166. Fraction to Recurring Decimal

Given two integers representing the numerator and denominator of a fraction, return the fraction in string format. If the fractional part is repeating, enclose the repeating part in parentheses.

知之可否 474

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

leetcode 166. Fraction to Recurring Decimal

166. Fraction to Recurring Decimal https://www.cnblogs.com/grandyang/p/4238577.html 用一个哈希表判断余数是否重复,重复了就有无限循环小数,就可以停止加括号了 class Solution { public: string fractionToDecimal(int numerator, int...

weixin_30596735的博客 188

[LeetCode] 166. Fraction to Recurring Decimal

LeetCode

稻穗小站 323

LeetCode 166. Fraction to Recurring Decimal

166. Fraction to Recurring Decimal Given two integers representing the numerator and denominator of a fraction, return the fraction in string format. If the fractional part is repeating, enclose t

柳婼 の blog 547

LeetCode - 解题笔记 - 166 - Fraction to Recurring Decimal

Solution 1 分数除法,先学习了。【官方题解】 首先最基本的,根据实际的取值范围存在溢出可能,因此先整体转为长整型。 然后判断结果是否为整数,即可直接计算分数除法然后输出。 否则,按照“符号位→整数部分和小数点→小数部分→循环节确认” 符号位,经典异或运算符应用 整数部分和小数点,直接除法 分数部分,根据余数确定逐个位的结果 循环节确认,基于规律“同余数的结果必然相同”,因此一旦出现相同余数也就意味着存在循环节,用哈希表保存第一次出现的位置,根据该位置插入括号 时间复杂度:O(M)O(M)O(

支锦铭的博客 294

Fraction to Recurring Decimal 166

题目描述: 给出一个小数的分子和分母,将这个小数转化成string类型表示的小数形式 当小数出现循环时,用小括号将循环节括起来 题目分析: 这个题目重点是找到循环节 对于存在循环节的情况,找到循环节是重点,   当什么情况下循环节完整的出现了呢?   我们不断的做除法,每次都会有一个余数,如果当前的余数在之前出现过,那么循环节就完整的出现了 代码: 1 typ...

weixin_30710457的博客 65

[LeetCode]166. Fraction to Recurring Decimal

Problem DescriptionGiven two integers representing the numerator and denominator of a fraction, return the fraction in string format.If the fractional part is repeating, enclose the repeating part in p

Narcssus的专栏 347

【LeetCode】166. Fraction to Recurring Decimal

Fraction to Recurring Decimal Given two integers representing the numerator and denominator of a fraction, return the fraction in string format. If the fractional part is repeating, enclose the repe...

weixin_34192732的博客 104
上一篇: 171. Excel Sheet Column Number (E)
下一篇: 172. Factorial Trailing Zeroes (E)
绿色小光头
博客等级 码龄10年 10粉丝 301原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值