338. Counting Bits, 338 countingbits

Source: Internet
Author: User

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 );}}}

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.