#leetcode#Fraction to Recurring Decimal
来源:互联网 发布:能看伪恋的漫画软件 编辑:程序博客网 时间:2024/05/17 07:47
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)".
解题思路是首先判断正负, 这里用了异或的方法来判断: (numerator > 0)^(denominator > 0) == 1 --> 是负数
然后整数部分很好得到, 直接 stringBuilder.append(numerator / denominator) 就可以了,
然后是小数部分的判断, 首先 append('.'), 每次计算取余数 remainder, 并把remainder作为key, 当前 stringbuilder的长度作为value存入hashmap,则当remainder重复出现时我们知道这个除法运算进入了无限循环, 加括号跳出循环。
有很多corner case,比如 -1 / -2147483648, 所以用long来防止溢出,
public class Solution { public String fractionToDecimal(int numerator, int denominator) { if(numerator == 0) return "0"; StringBuilder sb = new StringBuilder(); if((numerator > 0) ^ (denominator > 0)) sb.append('-'); long num = Math.abs((long)numerator); long den = Math.abs((long)denominator); sb.append(num / den); if(num % den == 0) return sb.toString(); sb.append("."); Map<Long, Integer> map = new HashMap<>(); while(num != 0){ long remainder = num % den; if(!map.containsKey(remainder)){ map.put(remainder, sb.length()); remainder *= 10; sb.append(remainder / den); num = remainder % den; }else{ sb.insert(map.get(remainder), "("); sb.append(")"); break; } } return sb.toString(); }}
0 0
- [leetcode] Fraction to Recurring Decimal
- LeetCode Fraction to Recurring Decimal
- Fraction to Recurring Decimal leetcode
- leetcode:Fraction to Recurring Decimal
- [LeetCode] Fraction to Recurring Decimal
- [leetCode] Fraction to Recurring Decimal
- LeetCode:Fraction to Recurring Decimal
- Leetcode: Fraction to Recurring Decimal
- Leetcode: Fraction to Recurring Decimal
- [LeetCode] Fraction to Recurring Decimal
- [LeetCode]Fraction to Recurring Decimal
- leetcode:Fraction to Recurring Decimal
- [LeetCode]Fraction to Recurring Decimal
- Leetcode: Fraction to Recurring Decimal
- [leetcode]Fraction to Recurring Decimal
- LeetCode: Fraction to Recurring Decimal
- [LeetCode] Fraction to Recurring Decimal
- leetcode: Fraction to Recurring Decimal
- 开始刷leetcode day63:Invert Binary Tree
- [Leetcode] Two Sum
- 开始刷leetcode day63: Contains Duplicate
- 开始刷leetcode day63:Contains Duplicate II
- 开始刷leetcode day63:Contains Duplicate III
- #leetcode#Fraction to Recurring Decimal
- 2015.07.12总结
- Qt Quick之StackView详解(2)
- 开始刷leetcode day63:House Robber II
- Leetcode NO.235 Lowest Common Ancestor of a Binary Search Tree
- IDC中招刷流量病毒,无法访问的解决过程
- 连接池
- 深入Java核心 Java内存分配原理精讲
- MVC模式