码迷,mamicode.com
首页 > 其他好文 > 详细

292. Nim Game

时间:2016-04-11 18:43:57      阅读:118      评论:0      收藏:0      [点我收藏+]

标签:

  从今天开始,每天刷一道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);
        }
    }
}

 

292. Nim Game

标签:

原文地址:http://www.cnblogs.com/wwwglin/p/5379341.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!