Root of Equation

题目:

Given an equation: ax^2 + bx + c = 0. Find the root of the equation.

If there are two roots, return a list with two roots in it.
If there are only one root, return a list with only one root in it.
If there are no root for the given equation, return an empty list.

补充: (2016-10-30) 三个地方要注意

1. Arrays.sort(E)语法
2. double[] res = new double[2]语法
3. 就算你希望 res = new double[0]也必须初始化 否则compiler报warning,不是很理想

分析:

1. 注意Math.sqrt(xxx)
2. 注意新建double[]的方法是 double[] res = new double[2];
这里面是double而不是<Double>,大概java的意思是在<>里面需要首字母大写,外加全称

解法:

public class Solution {
    /**
     * @param a, b, c: parameters of the equation
     * @return a double array, contains at most two root
     */
    public double[] rootOfEquation(double a, double b, double c) {
        // Write your code here
        double discriminant = b * b - 4 * a * c;
        if (discriminant > 0) {
            double root1 = ( (-b + Math.sqrt(discriminant) ) / (2 * a) );
            double root2 = ( (-b - Math.sqrt(discriminant) ) / (2 * a) );
            double[] result = new double[2];
            result[0] = (root1 > root2) ? root2 : root1;
            result[1] = (root1 > root2) ? root1 : root2;
            return result;
        } else if (discriminant == 0) {
            double root1 = ( (-b + Math.sqrt(discriminant) ) / (2 * a) );
            double[] result = new double[1];
            result[0] = root1;
            return result;
        } else {
            double[] result = new double[0];
            return result;
        }
    }
}

results matching ""

    No results matching ""