166. 分数到小数

166. 分数到小数

题目描述

给定两个整数,分别表示分数的分子 numerator 和分母 denominator,以 字符串形式返回小数

如果小数部分为循环小数,则将循环的部分括在括号内。

如果存在多个答案,只需返回 任意一个

对于所有给定的输入,保证 答案字符串的长度小于 10^4

示例 1:

输入:numerator = 1, denominator = 2
输出:"0.5"

示例 2:

输入:numerator = 2, denominator = 1
输出:"2"

示例 3:

输入:numerator = 2, denominator = 3
输出:"0.(6)"

示例 4:

输入:numerator = 4, denominator = 333
输出:"0.(012)"

示例 5:

输入:numerator = 1, denominator = 5
输出:"0.2"

提示:

  • -2^31 <= numerator, denominator <= 2^31 - 1
  • denominator != 0

题解:

模拟。

手动模拟整数除法,这个过程在纸上画画就明白了。

关键是怎么找循环节?

使用哈希表记录每个余数,当一个余数出现两次时,就出现了循环节。

时间复杂度: O ( n ) O(n) O(n)

额外空间复杂度: O ( 1 ) O(1) O(1)

class Solution {
public:
    using LL = long long;
    string fractionToDecimal(int numerator, int denominator) {
        LL x = numerator, y = denominator;
        if ( x % y == 0 ) 
            return to_string(x / y);
        bool is_neg = (x >> 31) ^ (y >> 31);
        if( x < 0 ) x = -x;
        if( y < 0 ) y = -y;
        unordered_map<LL, int> hash;
        string ret;
        if( is_neg ) ret.push_back( '-' );
        ret += to_string(x / y) + '.';
        x %= y;
        while( x ) {
            if ( hash.count( x ) ) {
                ret = ret.substr(0, hash[x]) + '(' + ret.substr(hash[x]) + ')';
                break;
            }
            hash[x] = ret.size();
            x *= 10;
            ret += to_string(x / y);
            x %= y;
        }
        return ret;
    }
};
/*
时间:0ms,击败:100.00%
内存:6.2MB,击败:80.65%
*/
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值