Leetcode Fraction to Recurring Decimal

Leetcode Fraction to Recurring Decimal,本题没有其它特别的,只是用map记录了相关位置的值、余数、以及位置,相关解题算法如下:

#include<iostream>
#include<string>
#include<map>

using namespace std;
class Solution {
public:
    string fractionToDecimal(int numerator, int denominator) {
        if (denominator == 0) {
            return "";
        }
        if (numerator == 0) {
            return "0";
        }
        // Use the long long int to prevent the int32 overflow
        long long int num1 = numerator;
        long long int num2 = denominator;
        if (num1 >= 0 ^ num2 >= 0) {
            re = "-";
        }
        if (num1 < 0) {
            num1 = -num1;
        }
        if (num2 < 0) {
            num2 = -num2;
        }
        string re = "";
        string tmp = "";
        tmp = to_string(num1 / num2);
        re += tmp;
        long long int left  = num1 % num2;
        char digit;
        string fraction = "";
        map<string, int> recursive;
        map<string, int>::iterator it;
        while (left != 0) {
            digit = left * 10 / num2 + '0';
            left = (left * 10) % num2;
            tmp = "";
            tmp.push_back(digit);
            tmp = tmp + "," + to_string(left);
            // Find the conrespond position in the priveous position to find
            // the recurring position
            it = recursive.find(tmp);
            if (it != recursive.end()) {
                fraction.push_back(' ');
                fraction.push_back(')');
                for (int i = fraction.length() - 2; i > it->second; i --) {
                    fraction[i] = fraction[i - 1];
                }
                fraction[it->second] = '(';
                break;
            } else {
                recursive[tmp] = fraction.length();
                fraction.push_back(digit);
            }
        }
        if (fraction != "") {
            re = re + "." + fraction;
        }
        return re;
    }
};

// Sample input: ./a.out argv1 argv2
int main(int argc, char* argv[]) {
    Solution so;
    string re = so.fractionToDecimal(atoi(argv[1]), atoi(argv[2]));
    cout<<"result: "<<re<<endl;
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值