很水,但是需要练速度反映。。。15分钟全部写对!!!!!!!!!!!!
#include <assert.h>
#include <algorithm>
#include <vector>
using namespace std;
class Decimal {
public:
int integer;
bool recycle;
vector<int> decimal;
};
void toDecimal(int dividend, int divisor, Decimal& decimal) {
decimal.integer = dividend / divisor;
int remainder = dividend % divisor, recycle = 0, end = 0, curbit = 0;
while (remainder) {
int cur = remainder*10/divisor;
decimal.decimal.push_back(cur);
if (recycle || curbit > 0)
recycle = decimal.decimal[recycle] == cur ? recycle + 1 : 0;
if (curbit > 0 && recycle == end) {
decimal.decimal.resize(recycle);
decimal.recycle = true;
return;
}
++curbit;
if (!recycle)
end = curbit;
remainder = (remainder * 10) % divisor;
}
decimal.recycle = false;
}
int main() {
Decimal dec;
toDecimal(12,8,dec);
return 0;
}
--------------------------------------------------------------------------------
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.
Example 1:
Input: numerator = 1, denominator = 2 Output: "0.5"
Example 2:
Input: numerator = 2, denominator = 1 Output: "2"
Example 3:
Input: numerator = 2, denominator = 3 Output: "0.(6)"
----------------------------------------------------------------------------------
class Solution:
def fractionToDecimal(self, numerator: int, denominator: int) -> str:
if (denominator == 0):
return None
op = "-" if ((numerator < 0 and denominator > 0) or (numerator > 0 and denominator < 0)) else ''
n1, n2 = numerator if numerator > 0 else -numerator, denominator if denominator > 0 else -denominator
p1, cur_mode, p2_lst, idx = n1//n2, n1%n2, [], 0
dic = {cur_mode: 0}
while (cur_mode != 0):
cur_mode *= 10
nxt_mode = cur_mode%n2
digit = cur_mode//n2
p2_lst.append(str(digit))
idx += 1
if (nxt_mode in dic):
return "{0}{1}.{2}({3})".format(op, p1, ''.join(p2_lst[:dic[nxt_mode]]) ,''.join(p2_lst[dic[nxt_mode]:]))
elif (nxt_mode == 0):
return "{0}{1}.{2}".format(op, p1, ''.join(p2_lst))
else:
dic[nxt_mode] = idx
cur_mode = nxt_mode
return "{0}{1}".format(op, p1)