Count 1s
import java.io.*;
import java.util.*;
class Solution {
public static void main(String[] args) {
Solution solution = new Solution();
int[][] input = {
null,
{},
{1},
{0,1},
{0,0,0,1},
{1,1,1,1,1,1},
{0},
{0,0,0,1,1},
{0,1,1,1,1,}
};
for(int i=0;i<input.length;i++) {
System.out.println("Input: " + Arrays.toString(input[i]) +
", Result: " + solution.count1s(input[i]));
}
}
public int count1s(int[] input) {
if(input == null || input.length < 1){
return 0;
}
return count1s(input, 0, input.length-1);
}
private int count1s(int[] input, int start, int end) {
if(start > end) {
return 0;
}
if(input[end] == 0){
return 0;
}
if(input[start] == 1) {
return end - start +1;
}
int mid = (start + end)/2;
return count1s(input,start,mid) + count1s(input,mid+1,end);
}
}