1. 程式人生 > >leetcode學習筆記35

leetcode學習筆記35

166. 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.

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)”

class Solution {  
    public String fractionToDecimal(int numerator, int denominator) {
    	StringBuffer res=new StringBuffer();
        long num=numerator,deno=denominator;
    	if
(numerator==0) return "0"; //1.判斷符號 int sign=1; if(num<0) { sign=-sign; num=Math.abs(num); } if(deno<0){ sign=-sign; deno=Math.abs(deno); } if(sign==-1) { res.append("-"); } //2.算整數部分 long res_num=num/deno; num=
num%deno; res.append(res_num); //3.算小數部分 if(num!=0){ res.append("."); StringBuffer res_decimal=new StringBuffer(); HashMap<Long,Integer> hm=new HashMap<Long,Integer>(); int index=0; while(num!=0){ num*=10; if(hm.containsKey(num)){ res_decimal.insert(hm.get(num),"("); res_decimal.append(")"); break; } hm.put(num,index++); res_num=num/deno; num=num%deno; res_decimal.append(res_num); } res.append(res_decimal); } return res.toString(); } }