您的位置:首页 > 其它

leetcode:Fraction to Recurring Decimal

2015-10-07 11:18 483 查看
原题如下:

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.

For example,

•Given numerator = 1, denominator = 2, return “0.5”.

•Given numerator = 2, denominator = 1, return “2”.

•Given numerator = 2, denominator = 3, return “0.(6)”.

原题地址:https://leetcode.com/problems/fraction-to-recurring-decimal/

需要注意的地方:

1、溢出,可观察如下输出结果,一定在使用a之前强制转换。

int a  = -2147483648;
long a1 = Math.abs(a);  //输出  -2147483648
long a2 = Math.abs((long)a);  //输出 2147483648


2、分数都是有理数,都是有限小数或者无限循环小数

3、String vs StringBuilder

下面是代码:

import java.util.HashMap;

public class Solution{

//解这个题需要注意:分数一定是有理数,即分数转化为小数时一定是有限小数或者无限循环小数
//理解String与StringBuilder的区别,String是字符串常量,每次操作都是建一个新的变量,而StringBuilder是字符串变量
public String fractionToDecimal(int numerator, int denominator) {
StringBuilder res  = new StringBuilder();
long zi = Math.abs((long)numerator),mu = Math.abs((long)denominator);

//判断符号
if(!(numerator<0==denominator<0) && numerator !=0){
res.append("-");
}
long reminder = zi%mu;
long divide = zi/mu;
if(reminder==0){    //能除尽,不产生小数
res.append(divide);
return res.toString();
}
res.append(divide);
res.append(".");

//下面开始计算小数,一旦出现相同的小数,即出现循环
//用map记录小数的位置,只有第一个小数的位置有用
//注意:当余数不为零的时候,除法运算就是不断将余数乘以10,然后再求除数与余数,不断循环的过程
//所以一旦出现相同的余数,那么就是一个循环
HashMap<Long,Integer> map = new HashMap<Long,Integer>();
while(!map.containsKey(reminder)){
map.put(reminder, res.length());
res.append(10*reminder/mu);
reminder = 10*reminder%mu;
}

int index = map.get(reminder);
res.insert(index, "(");
res.append(")");
return res.toString().replace("(0)", "");
}

public static void main(String[] args) {
Solution s = new Solution();
System.out.println(s.fractionToDecimal(-1, -2147483648));
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: