Java程序片段

1. 根据开始时间和结束时间获取时间长度

    import org.apache.commons.lang3.time.DurationFormatUtils;
    import org.apache.commons.lang3.time.DateUtils;

    public static String getDurationTime(Date begin, Date end) {
        String format = "";
        long durationTime = end.getTime() - begin.getTime();
        if (durationTime < DateUtils.MILLIS_PER_MINUTE) {
            format = "s秒";
        } else if (durationTime <= DateUtils.MILLIS_PER_HOUR) {
            format = "m分钟s秒";
        } else if (durationTime <= DateUtils.MILLIS_PER_DAY) {
            format = "H小时m分钟s秒";
        } else {
            format = "d天H小时m分钟s秒";
        }
        return DurationFormatUtils.formatDuration(durationTime, format);
    }

2. 求最大公约数

    public static int gcd(int p, int q) {
        if (q == 0)
            return p;
        int r = p % q;
        return gcd(q, r);
    }

3. 二分查找

    //数组a需要提前排序
    public static int rank(int key, int[] a) {
        int lo = 0;
        int hi = a.length - 1;
        while (lo <= hi) {
            int mid = lo + (hi - lo) / 2;
            if (key < a[mid])
                hi = mid - 1;
            else if (key > a[mid])
                lo = mid + 1;
            else
                return mid;
        }
        return -1;
    }

4. 判断一个数是不是素数

    public static boolean isPrime(int N) {
        if (N < 2)
            return false;
        for (int i = 2; i * i <= N; i++)
            if (N % i == 0)
                return false;
        return true;
    }

5. 求平方根的算法

    public static double sqrt(double c) {
        if (c < 0.0)
            return Double.NaN;
        double err = 1e-15;
        double t = c;
        while (Math.abs(t - c / t) > err * t)
            t = (c / t + t) / 2.0;
        return t;
    }

你可能感兴趣的:(Java程序片段)