VMWare Inc Interview Question
Software Engineer in Testspublic static int counteOne(int[] arr){
if(arr.length < 0){
return 0;
}
int counter = 0;
for(int i = 0; i < arr.length; i++){
if(arr[i] ==1){
counter ++;
}
}
return counter;
}
import java.util.ArrayList;
import java.util.List;
public class ArrayBytes {
public static void main(String[] args) {
List<String> arrayOfBytes = new ArrayList<String>(5);
// sample binary number starting from 10 to 15
// will be initially stored in array-
for (int j = 10; j < 15; j++) {
arrayOfBytes.add(Integer.toBinaryString(j));
}
long count = 0;
for (String string : arrayOfBytes) {
System.out.println(string);
char[] charArray = string.toCharArray();
for (char c : charArray) {
if (c == '1') {
count++;
}
}
}
// total count of 1 in all the elements of the array printed here
System.out.println(count);
}
}
In java i have:
public static int numOfOnes(byte[] byteArr){
int count = 0;
for(byte b: byteArr)
count += countOnes(b);
return count;
}
private static int countOnes(byte b){
int count=0;
for (int i=0; i<8; i++)
count+= (b>>i)&1;
return count;
}
This should take up O(1) space and O(n) time complexity.
I think the idea is using a method that has an O(1) in finding the number of ones ....
- moussa April 09, 2011So may be we should have precomputed 256 values in of a 8bits byte and inserted inside a Hash or Lookup Table. then if the array has a size of N, we can do it in O(N).