LeetCode Top Interview Questions 166. Fraction to Recurring Decimal (Java版; Medium)
题目描述
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)"
第一次做; 核心: 除式的计算流程; 边界情况:1)分子为0, 2)有一个数是-2147483648; 细节:注意区分全局的余数和局部的余数, 哈希表中记录的是局部的余数; 借助异或判断符号
class Solution {
public String fractionToDecimal ( int numerator, int denominator) {
if ( numerator == 0 )
return "0" ;
StringBuilder res = new StringBuilder ( ) ;
res. append ( ( numerator > 0 ) ^ ( denominator > 0 ) ? "-" : "" ) ;
long nu = Math. abs ( ( long ) numerator) ;
long de = Math. abs ( ( long ) denominator) ;
res. append ( nu / de) ;
nu = nu % de;
if ( nu == 0 )
return res. toString ( ) ;
res. append ( "." ) ;
HashMap< Long, Integer> map = new HashMap < > ( ) ;
map. put ( nu, res. length ( ) ) ;
while ( nu != 0 ) {
nu = nu * 10 ;
res. append ( nu / de) ;
nu = nu % de;
if ( map. containsKey ( nu) ) {
res. insert ( map. get ( nu) , "(" ) ;
res. append ( ")" ) ;
break ;
}
map. put ( nu, res. length ( ) ) ;
}
return res. toString ( ) ;
}
}
public class Solution {
public String fractionToDecimal ( int numerator, int denominator) {
if ( numerator == 0 ) {
return "0" ;
}
StringBuilder res = new StringBuilder ( ) ;
res. append ( ( ( numerator > 0 ) ^ ( denominator > 0 ) ) ? "-" : "" ) ;
long num = Math. abs ( ( long ) numerator) ;
long den = Math. abs ( ( long ) denominator) ;
res. append ( num / den) ;
num %= den;
if ( num == 0 ) {
return res. toString ( ) ;
}
res. append ( "." ) ;
HashMap< Long, Integer> map = new HashMap < Long, Integer> ( ) ;
map. put ( num, res. length ( ) ) ;
while ( num != 0 ) {
num *= 10 ;
res. append ( num / den) ;
num %= den;
if ( map. containsKey ( num) ) {
int index = map. get ( num) ;
res. insert ( index, "(" ) ;
res. append ( ")" ) ;
break ;
}
else {
map. put ( num, res. length ( ) ) ;
}
}
return res. toString ( ) ;
}
}