apachecn / apachecn-algo-zh

ApacheCN 数据结构与算法译文集
https://algo.apachecn.org/
11.03k stars 2.19k forks source link

improve the time complexity from O(n^2) to O(n) #215

Closed mcrwayfun closed 5 years ago

mcrwayfun commented 5 years ago

method1 and method2 can get same answer , but the time complexity of method2 is O(n) while method1 is O(n^2)

   // method1
    private boolean isBit1(int val, int index) {
        for (int i = 0; i < index; ++i) {
            val = val >> 1;
        }
        return (val & 1) == 1;
    }
   // method2
    private boolean isBit1(int val, int index) {
        val = val >> index;
        return (val & 1) == 1;
    }