[leetcode] Fraction to Recurring Decimal

  1. 没想到溢出这码事儿。。。纠结了好久。。。abs只能针对int所以得自己做abs。。。
  2. 需要记录循环开始的位置
#include <iostream>
#include <vector>
#include <string>
#include <map>
#include <sstream>
using namespace std;

string fractionToDecimal(int numerator, int denominator) {
    string res("");
    if (denominator == 0) return res;

    stringstream ss;
    // 负号
    if ((numerator > 0 && denominator < 0) || (numerator < 0 && denominator > 0)) {
        ss << "-";
    }

    // 防止溢出 (-2147483648, -1) (-1, -2147483648)
    long numer = numerator < 0 ? ((long)numerator * (-1)) : ((long)numerator);
    long denom = denominator < 0 ? (long)denominator * (-1) : (long)denominator;

    cout << numer << " " << denom << endl;
    long integer_part = numer / denom;
    ss << integer_part;
    cout << "integer_part : " << integer_part << endl;
    long remainder = numer % denom; // 余数
    cout << "remainder : " << remainder << endl;
    if (remainder == 0) {
        return ss.str();
    } else {
        ss << ".";
    }

    map<long, int> remainder_map;
    bool is_recurring = false;
    int decimal_index = 0; // pos
    stringstream decimal_ss;

    while(remainder != 0) {
        if (remainder_map.find(remainder) != remainder_map.end()) {
            is_recurring = true;
            break;
        } else {
            long tmp_value = (remainder * 10) / denom;
            remainder_map[remainder] = decimal_index;
            remainder = (remainder * 10) % denom;
            decimal_ss << tmp_value;
            cout << "tmp_value : " << tmp_value << " ; remainder : " << remainder << endl;
        }
        ++decimal_index;
    }

    if (is_recurring) {
        int pos = remainder_map[remainder];
        string decimal_part = decimal_ss.str();
        if (pos > 0) ss << decimal_part.substr(0, pos);
        ss << "(";
        ss << decimal_part.substr(pos, decimal_part.size() - pos);
        ss << ")";
    } else {
        ss << decimal_ss.str();
    }
    return ss.str();
}

int main()
{
    string res = fractionToDecimal(-1, -2147483648);
    cout << res << endl;
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值