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

【Leetcode 166】 Fraction to Recurring Decimal

时间:2016-09-11 22:43:02      阅读:150      评论:0      收藏:0      [点我收藏+]

标签:

Description:

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

Solution:

  long division: 长除法

  Trick: Determining whether two nums have different sign(+ or  -) can use follow codes:

if((n<0)^(d<0))  //异号
or
if((n>0)^(d>0))  //异号

  Above code avoiding product‘s value overflow.

Code:

class Solution {
public:
    string fractionToDecimal(int numerator, int denominator) {
        if(!numerator) return "0";
        long long n = numerator, d = denominator;
        string ret = "";
        if((n<0)^(d<0)) ret += -;
        if(n < 0) n = -n;
        if(d < 0) d = -d;
        ret += to_string(n/d);
        if(n % d == 0){
            return ret;
        }ret += .;
        map<long long, int>hash;
        for(long long r = n % d; r; r %= d){
            if(hash.find(r) != hash.end()){
                ret.insert(hash[r],"(");
                ret += ")";
                return ret;
            }
            hash[r] = ret.size();
            r *= 10;
            ret += to_string(r / d);
        }
    }
};

 

【Leetcode 166】 Fraction to Recurring Decimal

标签:

原文地址:http://www.cnblogs.com/luntai/p/5862823.html

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