分数转化为小数LeetCode 166. Fraction to Recurring Decimal

265 篇文章 1 订阅

很水,但是需要练速度反映。。。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)

 

 

 

 

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值