首页 > 代码库 > Fraction to Recurring Decimal
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.
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 }
Fraction to Recurring Decimal
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。