338. Counting Bits, 338 countingbits
Starting from today, refresh a leetcode every day.
Today's question is simple: Given a non negative integer number num. for every numbers I in the range 0 ≤ I ≤ num calculate the number of 1's in their binary representation and return them as an array.
Preliminary thought: double loop, number of Outer Loops, number of occurrences of '1' in the inner layer.
New knowledge: ArrayList to int array mode;
Hexadecimal conversion.
Solution:
Package com. wang. test; import java. util. arrayList; import java. util. list;/* @tittle * 338. counting Bits * Given a non negative integer number num. * For every numbers I in the range 0 ≤ I ≤ num * calculate the number of 1's in their binary representation and return them as an array. * @ auther: wanglin * @ time: 2016/04/11 */public class CountingBits {public int [] countBits (int num) {List list = new ArrayList (); for (int n = 0; n <= num; ++ n) {// binaryNum receives the binary String binaryNum = Integer. toBinaryString (n); char [] charArr = binaryNum. toCharArray (); int I = 0; for (int m = 0; m <charArr. length; ++ m) {if (charArr [m] = '1') {I ++ ;}} list. add (I);} int [] res = new int [list. size ()]; for (int I = 0; I <list. size (); I ++) {res [I] = (Integer) list. get (I);} return res;} public static void main (String [] args) {int [] res = new CountingBits (). countBits (5); for (int I: res) {System. out. print (I );}}}