Fraction to Recurring Decimal (Java)

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

這道題和divide two integer那道題不同,這道題可以直接使用除號和取模運算。但應該注意的是abs在使用前一定要將數據先轉爲long型。否則對於int型的minvalue會失效。這道題和divide two integer測試數據不同的是 輸入-2147483648, -1會輸出2147483648,不會溢出成maxvlue,所以不用管這個特殊情況。另外注意hashmap沒存值時初始爲null而非0。
Source
public class Solution {
    public String fractionToDecimal(int numerator, int denominator) {
    	long n = numerator, d = denominator;
    	if(n == 0) return "0";
    	
    	StringBuffer a = new StringBuffer();
    	if((n < 0) ^ (d < 0)) a.append("-");
    	
    	n = Math.abs(n);
    	d = Math.abs(d);
    	
    	long in = n / d;
    	a.append(String.valueOf(in));   //StringBuffer裏面沒有String的 a = a + 
    	
    	if(n % d == 0) return a.toString();
    	else a.append(".");
    	//以上是小數點以前的
    	
    	HashMap<Long, Integer> map = new HashMap<Long, Integer>();  //注意要用Long和Integer 不能用long和int
    	//用hashmap查找循環的地方比較方便
    	//System.out.println(map.get(0)); //打印可看出 integer位置上未初始化時存的是null
    	long i;
    	for(i = n % d; i != 0; i = i % d){	//注意step
    		if(map.get(i) != null) break;      
    		
    		map.put(i, a.length());		//將i的值當做key a的位置當做value
    		i *= 10;
    		
    		a.append(i / d);
    	}
    	if(i == 0) return a.toString();
    	a.insert(map.get(i), "(");  //直接在循環的地方加入(
    	a.append(")");		//出現循環就立即跳出了循環,也就是說從i的位置到最後,都是循環體,所以只需在最後面加上)
    	return a.toString();
    }
}


Test
 public static void main(String[] args){
    	int n = -2147483648, d = 1;
    	System.out.println(new Solution().fractionToDecimal(n, d));
  
    }


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章