从今天开始,每天刷一道leetcode。
今天的题目很简单: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.
初步思路:双循环,外层循环数字,内层统计‘1’出现次数。
新知识:ArrayList转int数组方式;
进制转换。
解决:
1 package com.wang.test; 2 3 import java.util.ArrayList; 4 import java.util.List; 5 6 /* @Tittle 7 * 338. Counting Bits 8 * Given a non negative integer number num. 9 * For every numbers i in the range 0 ≤ i ≤ num 10 * calculate the number of 1's in their binary representation and return them as an array. 11 * @auther:wanglin 12 * @time:2016/04/11 13 */ 14 public class CountingBits { 15 public int[] countBits(int num) { 16 List list = new ArrayList(); 17 for (int n = 0; n <= num; ++n) { 18 // binaryNum接收转为二进制的数字 19 String binaryNum = Integer.toBinaryString(n); 20 char[] charArr = binaryNum.toCharArray(); 21 int i = 0; 22 for (int m = 0; m < charArr.length; ++m) { 23 if (charArr[m] == '1') { 24 i++; 25 } 26 } 27 list.add(i); 28 } 29 int[] res = new int[list.size()]; 30 for (int i = 0; i < list.size(); i++) { 31 res[i] = (Integer) list.get(i); 32 } 33 return res; 34 } 35 36 public static void main(String[] args) { 37 int[] res = new CountingBits().countBits(5); 38 for (int i : res) { 39 System.out.print(i); 40 } 41 } 42 }