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、要判断数字正负,取绝对值再运算。一开始把0去掉,用^判断正负,如果用两数相乘判断正负所得结果可能溢出

2、HashMap存进去时候的顺序和取出来的顺序是不一致的,LinkedHashMap可以保持顺序一致,所以在这里我用了LinkedHashMap

3、:int_min的处理,转换成正数的时候会溢出,所以要转换成long再处理

代码如下:int

import java.util.LinkedHashMap;
public class Solution {
    public String fractionToDecimal(int numerator, int denominator) {
        if (numerator == 0) return "0";  
        if (denominator == 0) return "";  
        String result="";
        if ((numerator < 0) ^ (denominator < 0)) {  
        	result += "-";  
        }  
        long num = numerator, den = denominator;  
        num = Math.abs(num);  
        den = Math.abs(den);  
        //quotient商,reminder余数
        long quotient =num/den; 
        long reminder =num%den;
        result+=quotient;
        if(reminder==0)
        	return result;
        Map<Long, Integer> map=new LinkedHashMap<Long, Integer>();
        while(reminder!=0&&!map.containsKey(reminder)){
        	quotient=reminder*10/den;
        	map.put(reminder, (int) Math.abs(quotient));
        	reminder=reminder*10%den;
        }
        result+=".";
        if(reminder==0){
        	for(Long key:map.keySet()){
        		result+=map.get(key);
        	}
        }else{
        	for(Long key:map.keySet()){
        		if(key==reminder)
        			result+="(";
        		result+=map.get(key);
        	}result+=")";
        }
        return result;
    }
}


你可能感兴趣的:(java,LeetCode,HashMap,除法)