LeetCode Fraction to Recurring Decimal

原题链接在这里:https://leetcode.com/problems/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.

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)"

题解:

加入整数部分后,在reminder 不为0的时候添加小数部分,用HashMap来维护reminder 和 对应的小数长度. 若是出现无限循环可以找到加左括号的起始点.

AC Java:

 public class Solution {
public String fractionToDecimal(int numerator, int denominator) {
if(numerator == 0){
return "0";
}
if(denominator == 0){
return "";
} StringBuilder res = new StringBuilder();
long num = Math.abs((long)numerator);
long deno = Math.abs((long)denominator); //如果是负数
if((numerator < 0) ^ (denominator < 0)){
res.append("-");
} res.append(num/deno);
long reminder = num%deno;
if(reminder == 0){
return res.toString();
} //有小数
res.append(".");
//HashMap中计入reminder 和 对应的小数部分长度,用来找到循环开始的位置
HashMap<Long, Integer> hm = new HashMap<Long, Integer>();
StringBuilder desRes = new StringBuilder();
while(reminder != 0){
if(hm.containsKey(reminder)){ //出现了循环,找到循环开始的index添加左括号
int beginIndex = hm.get(reminder);
desRes.insert(beginIndex, "(");
desRes.append(")");
res.append(desRes);
return res.toString();
}
hm.put(reminder, desRes.length());
desRes.append(reminder*10/deno);
reminder = (reminder*10)%deno;
}
res.append(desRes);
return res.toString();
}
}

Decimal To Fraction 小数转换成分数类似.

上一篇:Android 单字阅读


下一篇:select 自匹配问题