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.

For example,

1、Given numerator = 1, denominator = 2, return "0.5".

2、Given numerator = 2, denominator = 1, return "2".

3、Given numerator = 2, denominator = 3, return "0.(6)".

<span style="font-size:18px;">public class Solution {
    public String fractionToDecimal(int numerator, int denominator) {
            boolean symbol = true;//默认是整数
		    if((numerator < 0 && denominator > 0) || (numerator > 0 && denominator < 0)){
			    symbol = false;//结果是负数
		    }
		    long numerator1 = Math.abs((long)numerator);
		    long denominator1 = Math.abs((long)denominator);
            String res = "";
		    ArrayList<Long> quotient = new ArrayList<Long>();//保存十分位,百分位...
        	ArrayList<Long> rem = new ArrayList<Long>();//保存小数位对应的余数
		    long num = numerator1/denominator1;      //保存整数部分
        	long remainder = numerator1%denominator1;//取余,开始小数部分的计算
		    quotient.add(num);//保存整数部分的整数
		    rem.add(remainder);//保存整数部分的余数
        	while(remainder != 0){//存在小数部分
                while(remainder < denominator1){
                    remainder = remainder * 10; //新的分子
                    if(remainder > denominator1){
                        break;
                    }
                    quotient.add(0L);
                    rem.add(Math.abs(remainder));
                }
			    //num = remainder * 10; //新的分子
			    quotient.add(Math.abs(remainder/denominator1));//对应小数位的商
			    remainder = remainder % denominator1;
			    if(rem.contains(remainder)){
                		break;	 
            	}
			    rem.add(Math.abs(remainder));//对应小数位的余数	
        	}
        	int n = -1;
        	if(quotient.size() == 1){//只有整数部分
            		res = res + quotient.get(0);
        	}else{//存在小数部分
			        res = res + quotient.get(0) + '.';
            		if(remainder != 0){//存在循环节
                		n = rem.indexOf(remainder) + 1;//保存循环节所对应的小数位置
            		}
			        for(int i = 1 ; i < quotient.size() ; i ++){
            			if(i == n ){
                			res = res  + "(" + quotient.get(i) ;
            			}else{
                			res = res + quotient.get(i);
            			}
        		    }
        		    if(n > -1){
            			    res = res + ")";
        		    }	
		    }	
        	if(!symbol){
        	    if(quotient.get(0) >= 0){
        	        res = '-' + res;
        	    }
        	}
		   	return res;	
    }
}</span>

做过之后,深深感到自己的编程能力是如此之烂,题目不难,就是一个除法的过程,但是真正写起来,错误百出。 

1、这个过程不能完整的描述出来,过程描述出来了,编程也就简单了

2、问题考虑的不全面,比如,正负号的问题,当分母是-2147483648时的处理

3、数据类型问题,该用何种类型盛装

4、循环节的记录

5、更简便的算法尚未想出,希望各位大哥大姐不吝赐教,提出宝贵的思路!

革命尚未成功,吾辈仍需努力!

你可能感兴趣的:(TO,LeetCode,fraction,Recurrin)