【LeetCode】166. Fraction to Recurring Decimal 分数到小数(Medium)(JAVA)

【LeetCode】166. Fraction to Recurring Decimal 分数到小数(Medium)(JAVA)

题目地址: https://leetcode.com/problems/fraction-to-recurring-decimal/

题目描述:

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.

If multiple answers are possible, return any of them.

It is guaranteed that the length of the answer string is less than 10^4 for all the given inputs.

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)"

Example 4:

Input: numerator = 4, denominator = 333
Output: "0.(012)"

Example 5:

Input: numerator = 1, denominator = 5
Output: "0.2"

Constraints:

  • -2^31 <= numerator, denominator <= 2^31 - 1
  • denominator != 0

题目大意

给定两个整数,分别表示分数的分子 numerator 和分母 denominator,以 字符串形式返回小数 。

如果小数部分为循环小数,则将循环的部分括在括号内。

如果存在多个答案,只需返回 任意一个 。

对于所有给定的输入,保证 答案字符串的长度小于 10^4 。

解题方法

  1. 先把负的变为正的(考虑到存在负数的情况)
  2. numerator / denominator 结果存起来,(numerator % denominator) * 10 作为下一个的 numerator
  3. 如何判断结果开始重复了呢?就需要把前面的 numerator 存起来,只要 numerator 重复了,就说明结果也开始重复了(note: 结果用 map 存,key = numerator, value = res.length())
  4. note: 这题的细节有点多,提交了五六遍才过:1、存在负数的情况;2、(numerator % denominator) * 10 计算的时候 int 可能超限
class Solution {
    public String fractionToDecimal(int numerator, int denominator) {
        long first = numerator;
        long second = denominator;
        StringBuilder res = new StringBuilder();
        Map<Long, Integer> map = new HashMap<>();
        if (first < 0 && second < 0) {
            first = -first;
            second = -second;
        } else if (first < 0 && second > 0) {
            first = -first;
            res.append("-");
        } else if (first > 0 && second < 0) {
            second = -second;
            res.append("-");
        }
        while (map.get(first) == null) {
            long temp = first / second;
            res.append(temp);
            if (temp * second == first) return res.toString();
            if (map.size() == 0) {
                res.append(".");
            }
            map.put(first, res.length() - 1);
            first = first % second;
            first *= 10;
        }
        res.append(")");
        res.insert(map.get(first), "(");
        return res.toString();
    }
}

执行耗时:1 ms,击败了100.00% 的Java用户
内存消耗:35.8 MB,击败了86.43% 的Java用户

欢迎关注我的公众号,LeetCode 每日一题更新
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值