From today onwards, brush a leetcode every day.
Today's topic 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.
Initial thinking: double loop, outer loop number, inner layer statistics ' 1 ' occurrences.
New knowledge: ArrayList to int array mode;
Binary conversion.
Solve:
Packagecom.wang.test;Importjava.util.ArrayList;Importjava.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 th EM as an array. * @auther: Wanglin * @time: 2016/04/11*/ Public classCountingbits { Public int[] Countbits (intnum) {List List=NewArrayList (); for(intn = 0; n <= num; ++N) {//Binarynum receiving a number converted into binaryString Binarynum =integer.tobinarystring (n); Char[] Chararr =Binarynum.tochararray (); inti = 0; for(intm = 0; M < chararr.length; ++m) {if(Chararr[m] = = ' 1 ') {i++; }} list.add (i); } int[] res =New int[List.size ()]; for(inti = 0; I < list.size (); i++) {Res[i]=(Integer) list.get (i); } returnRes; } Public Static voidMain (string[] args) {int[] res =NewCountingbits (). Countbits (5); for(inti:res) {System.out.print (i); } }}
292. Nim Game