2019.8.21 #程序员笔试必备# LeetCode 从零单刷个人笔记整理(持续更新)
这题思路很简单,主要就是模拟小学长除法公式。有需要注意的几点:
1.对于分子或者分母为0的情况要特殊处理,题中没有给分母为0的默认返回值,解答里暂时省略,但实际面试的时候要询问。
2.对于负数情况和整除情况要进行考虑。
3.对无限循环小数要特殊处理。当出现重复的余数时会出现无限循环小数,可以用一个哈希表记录每一个余数对应的商的小数数位,一旦出现重复,在该位置和商的结尾处插入括号即可。
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.
给定两个整数,分别表示分数的分子 numerator 和分母 denominator,以字符串形式返回小数。
如果小数部分为循环小数,则将循环的部分括在括号内。
示例 1:
输入: numerator = 1, denominator = 2
输出: "0.5"
示例 2:
输入: numerator = 2, denominator = 1
输出: "2"
示例 3:
输入: numerator = 2, denominator = 3
输出: "0.(6)"
import java.util.HashMap;
/**
*
* 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.
* 给定两个整数,分别表示分数的分子 numerator 和分母 denominator,以字符串形式返回小数。
* 如果小数部分为循环小数,则将循环的部分括在括号内。
*
*/
public class FractionToRecurringDecimal {
public String fractionToDecimal