Fraction to Recurring Decimal

本文介绍了一个算法问题:如何将任意两个整数表示的分数转换为字符串格式的小数,并在重复部分使用括号标记。文章提供了详细的Java代码实现,涵盖了符号处理、整数与小数部分分离、重复小数检测等关键步骤。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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.

For example,

  • Given numerator = 1, denominator = 2, return "0.5".
  • Given numerator = 2, denominator = 1, return "2".
  • Given numerator = 2, denominator = 3, return "0.(6)".

 

这题很麻烦。

1。首先要判断符号, numberator 和 denominator 都是可正可负的。

2。numberator 要用long 否则会溢出。

3。每一次只能被减数*10,而且当没有出现小数点前,不会出现括号。所以先把整数部分和小数点全部输出,

 1 public class Solution {
 2     public String fractionToDecimal(int numerator, int denominator) {
 3         if(numerator == 0) return new String("0");
 4         StringBuilder sb = new StringBuilder();
 5         boolean o = (numerator < 0) ^ (denominator < 0);
 6         if(o) sb.append("-");
 7         long a = Math.abs((long)numerator);
 8         long b = Math.abs((long)denominator);
 9         sb.append(String.valueOf(a / b));
10         a = a % b;
11         if(a == 0) return sb.toString();
12         sb.append(".");
13         HashMap<Long, Integer> map = new HashMap<Long, Integer>();
14         for(int pos = sb.length(); a != 0; pos ++){
15             a *= 10;
16             if(map.containsKey(a)){
17                 sb.insert(map.get(a), "(");
18                 sb.append(")");
19                 break;
20             }
21             sb.append((int)(a / b));
22             map.put(a, pos);
23             a = a % b;
24         }
25         return sb.toString();
26     }
27 }

 

转载于:https://www.cnblogs.com/reynold-lei/p/4226748.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值