Java solution O(n) 4ms using Hamming weight alg


  • 0
    K

    My solution is based on Hamming weight

    public class Solution {
        public int[] countBits(int num) {
            int[] result = new int[num + 1];
            for(int i = 0 ; i <= num; i ++){
                result[i] = getBits(i);
            }
            return result;
        }
    
        private int getBits(int i ){
            i = i - ((i >>> 1) & 0x55555555);
            i = (i & 0x33333333) + ((i >>> 2) & 0x33333333);
            return (((i + (i >>> 4)) & 0x0F0F0F0F) * 0x01010101) >>> 24;
        }
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.