您的位置:首页 > 其它

Leetcode Fraction to Recurring Decimal

2015-11-24 11:33 295 查看
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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  算法 leetcode