338. Counting Bits,338countingbits

來源:互聯網
上載者:User

338. Counting Bits,338countingbits

  從今天開始,每天刷一道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數組方式;

      進位轉換。

  解決:

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接收轉為二進位的數字            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);        }    }}

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.