RecurringNumbers

来源:互联网 发布:最终幻想10 知乎 编辑:程序博客网 时间:2024/05/16 09:02
/*Problem Statement
         
A rational number is defined as a/b, where a and b are integers, and b is greater than 0.

Furthermore, a rational number can be written as a decimal that has a group of digits that repeat indefinitely.

A common method of writing groups of repeating digits is to place them inside parentheses like 2.85(23) = 2.852323 ... 23...

Given a decimal representation of a rational number in decimalNumber, convert it to a fraction formatted as "numerator/denominator",

where both numerator and denominator are integers.

The fraction must be reduced. In other words, the denominator must be as small as possible, but greater than zero.

Definition
         
Class:     RecurringNumbers
Method:     convertToFraction
Parameters:     String
Returns:     String
Method signature:     String convertToFraction(String decimalNumber)
(be sure your method is public)
    
Constraints
-     decimalNumber will have between 3 and 10 characters inclusive.
-     decimalNumber will contain only characters '0' - '9', '.', '(' and ')'.
-     The second character in decimalNumber will always be '.'.
-     There will be at most one '(' and ')' in decimalNumber.
-     '(' in decimalNumber will be followed by one or more digits ('0' - '9'), followed by ')'.
-     ')' in decimalNumber will not be followed by any other character.
Examples
0)     "0.(3)"        Returns: "1/3"        0.(3) = 0.333... = 1/3
1)     "1.3125"    Returns: "21/16"    Note there are no recurring digits here, although we could write it as 1.3125(0) or 1.3124(9).
2)     "2.85(23)"    Returns: "14119/4950"
2.85(23) = 2.852323... = 285/100 + 23/9900 = 28238/9900 = 14119/4950. Make sure to reduce the fraction, as shown in the final step.
3)     "9.123(456)"    Returns: "3038111/333000"
4)     "0.111(1)"    Returns: "1/9"
5)     "3.(000)"    Returns: "3/1"

This problem statement is the exclusive and proprietary property of TopCoder, Inc.
Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited.
(c)2003, TopCoder, Inc. All rights reserved. */

package recurringNumbers;

public class RecurringNumbers {
    static String intPart = null;
    static String stablePart = null;
    static String recPart = null;
    
    private static void checkFormat(String num) throws Exception{
        if(num.indexOf(".") == -1) {
            Integer.valueOf(num).intValue();
            intPart = num;
        }
        else {
            String[] values = new String[2];
            values[0] = num.substring(0, num.indexOf("."));
            values[1] = num.substring(num.indexOf(".") + 1);
            //if(values.length != 2) throw new NumberFormatException();
            
            Integer.valueOf(values[0]).intValue();
            intPart = values[0];
            
            if(!values[1].contains("(")) {
                Integer.valueOf(values[1]).intValue();
                stablePart = values[1];
            } else {
                if(! values[1].contains(")") || values[1].indexOf("(") > values[1].indexOf(")")) throw new NumberFormatException();
                
                if(values[1].indexOf("(") != 0){
                    Integer.valueOf(values[1].substring(0, values[1].indexOf("("))).intValue();
                    stablePart = values[1].substring(0, values[1].indexOf("("));
                }
                
                Integer.valueOf(values[1].substring(values[1].indexOf("(") + 1, values[1].indexOf(")"))).intValue();
                recPart = values[1].substring(values[1].indexOf("(") + 1, values[1].indexOf(")"));
            }
        }
    }

    public static String convertToFraction(String decimalNumber) throws Exception{
        
        checkFormat(decimalNumber);
        
        Real realInt = null;
        realInt = new Real(Integer.valueOf(intPart).intValue(), 1);
        
        Real realStable = null;
        if(stablePart != null) {
            StringBuffer temp = new StringBuffer();
            temp.append("1");
            for (int i = 0; i < stablePart.length(); i++) {
                temp.append("0");
            }
            realStable = new Real(Integer.valueOf(stablePart).intValue(), Integer.valueOf(temp.toString()).intValue());
        }
        
        Real realRec = null;
        if(recPart != null) {
            StringBuffer temp = new StringBuffer();
            for (int i = 0; i < recPart.length(); i++) {
                temp.append("9");
            }
            if(stablePart != null && stablePart.length() > 0) {
            for (int j = 0; j < stablePart.length(); j++) {
                temp.append("0");
            }
            }
            realRec = new Real(Integer.valueOf(recPart).intValue(), Integer.valueOf(temp.toString()).intValue());
        }
        
        Real result = realInt;
        if(realStable != null) result = Real.plus(result, realStable);
        if(realRec != null) result = Real.plus(result, realRec);
        
        
        return result.show();
    }
    

}

class Real {
    int num = 0;
    int den = 0;
    
    Real(int num, int den){
        int temp = gcd(num, den);
        if(temp != 0) {
            this.num = num/temp;
            this.den = den/temp;
        }
        else {
            this.num = num;
            this.den = den;
        }
    }
    
    int gcd(int a, int b) {
        if (b == 0) return a;
        
        if (b > a) return gcd(b, a);
        else return gcd(b, a % b);
    }
    
    String show() {
        StringBuffer temp = new StringBuffer();
        temp.append("result is:").append("  " + this.num).append("/" + this.den);
        return temp.toString();
    }
    
    static Real plus(Real a, Real b) {
        Real temp = new Real(a.num * b.den + a.den * b.num, a.den * b.den);
        return temp;
    }

}
原创粉丝点击