码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode-166 Fraction to Recurring Decimal

时间:2015-04-23 13:07:06      阅读:133      评论:0      收藏:0      [点我收藏+]

标签:

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

Credits:
Special thanks to @Shangrila for adding this problem and creating all test cases.

 

题意:将分数转换成小数

 

思路:用HashMap存已经计算过的分子,如果一个新的分子存在map中,则出现循环,因此用分子作为map的key就行。但是对于map的value该怎么定,出现了疑惑。

1. 用分子除以分母的整数值作为value,之后如果出现循环,只要看循环开始的value是什么,找到对应的位置插入()就好了,但是在1/90的case中出现问题;

2. 看到别人的代码中用不同分子时,对应的结果长度作为value,这样可以避免1中出现的问题;所以用这种方式报错value值。

 

可能会挂掉的case:

0/11

1/90;

1/2147483647(Integer.MAX_VALUE);

-1/2147483647;

1/-2147483638;

代码如下:

public String fractionToDecimal(int a1, int a2) {
        if(a1 == 0 || a2 == 0) return "0";
        StringBuilder sb = new StringBuilder();
        sb.append((a1>0) ^ (a2>0) ? "-":"");
        long a = Math.abs((long)a1);
        long b = Math.abs((long)a2);
        sb.append(Math.abs(a/b));
        a = (a % b) * 10;
        if(a != 0)    
            sb.append(".");
        
        Map<Long, Integer> map = new HashMap<Long, Integer>();
        map.put(new Long(a1), sb.length());
        while(a != 0) {
            sb.append(a/b);
            map.put(a, sb.length());
            
            a = (a % b) * 10;
            if(map.containsKey(a)) {
                int pos = map.get(a);
                sb.insert(pos-1, "(");
                sb.append(")");
                break;
            }
        }
        return sb.toString();
    }

在上述代码中,把输入转换为long类型进行计算的原因是:

1. 存在*10计算,用int可能会溢出;

2. 把Integer.MIN_VALUE转换为正数时,如果用int类型还是会溢出;

LeetCode-166 Fraction to Recurring Decimal

标签:

原文地址:http://www.cnblogs.com/linxiong/p/4450085.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!