当前位置:网站首页>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 面试题 17.20. 连续中值(大顶堆+小顶堆)
- Emballage automatique et déballage compris? Quel est le principe?
- QT detection card reader analog keyboard input
- Retinaface: single stage dense face localization in the wild
- About windows and layout
- 4G module IMEI of charging pile design
- CV learning notes - camera model (Euclidean transformation and affine transformation)
- My notes on intelligent charging pile development (II): overview of system hardware circuit design
- Leetcode bit operation
- CV learning notes alexnet
猜你喜欢

【C 题集】of Ⅵ

Leetcode-513:找树的左下角值

Yocto technology sharing phase IV: customize and add software package support

Opencv gray histogram, histogram specification

Working mode of 80C51 Serial Port

CV learning notes - camera model (Euclidean transformation and affine transformation)

Cases of OpenCV image enhancement

CV learning notes - deep learning

LeetCode - 460 LFU 缓存(设计 - 哈希表+双向链表 哈希表+平衡二叉树(TreeSet))*

CV learning notes - scale invariant feature transformation (SIFT)
随机推荐
20220605数学:两数相除
The data read by pandas is saved to the MySQL database
LeetCode - 673. Number of longest increasing subsequences
Leetcode - 460 LFU cache (Design - hash table + bidirectional linked hash table + balanced binary tree (TreeSet))*
CV learning notes - reasoning and training
Interruption system of 51 single chip microcomputer
Drive and control program of Dianchuan charging board for charging pile design
20220603数学:Pow(x,n)
4G module at command communication package interface designed by charging pile
LeetCode - 1670 設計前中後隊列(設計 - 兩個雙端隊列)
Leetcode-100:相同的树
20220602数学:Excel表列序号
CV learning notes - camera model (Euclidean transformation and affine transformation)
Opencv histogram equalization
ADS simulation design of class AB RF power amplifier
Opencv image rotation
Basic knowledge of communication interface
getopt_ Typical use of long function
Leetcode - 933 number of recent requests
LeetCode - 900. RLE 迭代器