当前位置:网站首页>20220606数学:分数到小数
20220606数学:分数到小数
2022-07-03 09:20:00 【丿SeeYouAgain】
题目描述:给定两个整数,分别表示分数的分子 numerator
和分母 denominator
,以 字符串形式返回小数 。如果小数部分为循环小数,则将循环的部分括在括号内。如果存在多个答案,只需返回 任意一个 。对于所有给定的输入,保证 答案字符串的长度小于 10^4
。
编码实现:
public String fractionToDecimal(int numerator, int denominator) {
if (denominator == 0) {
return "";
}
if (numerator == 0) {
return "0";
}
StringBuilder result = new StringBuilder();
long num = numerator,den = denominator;
if ((num >= 0) ^ (den >= 0)) {
result.append("-");
}
num = Math.abs(num);
den = Math.abs(den);
result.append(num / den);
num %= den;
if (num == 0) {
return result.toString();
}
result.append(".");
int index = result.length() - 1;
Map<Long, Integer> record = new HashMap<>();
while (num != 0 && !record.containsKey(num)) {
record.put(num, ++index);
num *= 10;
result.append(num / den);
num %= den;
}
if (record.containsKey(num)) {
result.insert(record.get(num), "(");
result.append(")");
}
return result.toString();
}
边栏推荐
- openEuler kernel 技術分享 - 第1期 - kdump 基本原理、使用及案例介紹
- Working mode of 80C51 Serial Port
- Google browser plug-in recommendation
- 使用密钥对的形式连接阿里云服务器
- ADS simulation design of class AB RF power amplifier
- Sending and interrupt receiving of STM32 serial port
- LeetCode - 919. 完全二叉树插入器 (数组)
- LeetCode 面试题 17.20. 连续中值(大顶堆+小顶堆)
- LeetCode - 508. 出现次数最多的子树元素和 (二叉树的遍历)
- Retinaface: single stage dense face localization in the wild
猜你喜欢
CV learning notes - clustering
Opencv notes 20 PCA
Leetcode - 460 LFU cache (Design - hash table + bidirectional linked hash table + balanced binary tree (TreeSet))*
There is no shortcut to learning and development, and there is almost no situation that you can learn faster by leading the way
CV learning notes - Stereo Vision (point cloud model, spin image, 3D reconstruction)
2021-10-28
LeetCode - 1670 設計前中後隊列(設計 - 兩個雙端隊列)
Leetcode 300 最长上升子序列
LeetCode - 508. 出现次数最多的子树元素和 (二叉树的遍历)
Leetcode - 933 number of recent requests
随机推荐
Opencv notes 20 PCA
Problems encountered when MySQL saves CSV files
Markdown latex full quantifier and existential quantifier (for all, existential)
Yocto technology sharing phase IV: customize and add software package support
Open Euler Kernel Technology Sharing - Issue 1 - kdump Basic Principles, use and Case Introduction
Gif image analysis drawing RGB to YUV table lookup method to reduce CPU occupancy
Development of intelligent charging pile (I): overview of the overall design of the system
使用密钥对的形式连接阿里云服务器
Opencv histogram equalization
Timer and counter of 51 single chip microcomputer
After clicking the Save button, you can only click it once
Dynamic layout management
2. Elment UI date selector formatting problem
20220610其他:任务调度器
openEuler kernel 技術分享 - 第1期 - kdump 基本原理、使用及案例介紹
Opencv Harris corner detection
Application of 51 single chip microcomputer timer
Opencv notes 17 template matching
yocto 技術分享第四期:自定義增加軟件包支持
pycharm 无法引入自定义包