当前位置:网站首页>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();
}
边栏推荐
- Leetcode-112:路径总和
- Leetcode-106:根据中后序遍历序列构造二叉树
- 4G module at command communication package interface designed by charging pile
- Leetcode-513:找树的左下角值
- 20220605数学:两数相除
- Dynamic layout management
- The data read by pandas is saved to the MySQL database
- STM32 general timer output PWM control steering gear
- Connect Alibaba cloud servers in the form of key pairs
- After clicking the Save button, you can only click it once
猜你喜欢

CV learning notes - edge extraction

Swing transformer details-2

Octave instructions

Opencv feature extraction - hog

My notes on intelligent charging pile development (II): overview of system hardware circuit design

CV learning notes - deep learning

CV learning notes - reasoning and training

CV learning notes - BP neural network training example (including detailed calculation process and formula derivation)

Installation and removal of MySQL under Windows

Leetcode 300 longest ascending subsequence
随机推荐
20220602数学:Excel表列序号
3.2 Off-Policy Monte Carlo Methods & case study: Blackjack of off-Policy Evaluation
Opencv notes 20 PCA
For new students, if you have no contact with single-chip microcomputer, it is recommended to get started with 51 single-chip microcomputer
CV learning notes - deep learning
20220609其他:多数元素
STM32 running lantern experiment - library function version
QT is a method of batch modifying the style of a certain type of control after naming the control
Markdown latex full quantifier and existential quantifier (for all, existential)
LeetCode - 1670 設計前中後隊列(設計 - 兩個雙端隊列)
Toolbutton property settings
Tensorflow built-in evaluation
El table X-axis direction (horizontal) scroll bar slides to the right by default
LeetCode - 706 设计哈希映射(设计) *
LeetCode - 705 设计哈希集合(设计)
Window maximum and minimum settings
QT detection card reader analog keyboard input
LeetCode - 933 最近的请求次数
20220531数学:快乐数
CV learning notes - camera model (Euclidean transformation and affine transformation)