领扣LintCode算法问题答案-1665. 计算数字

    科技2022-07-13  118

    领扣LintCode算法问题答案-1665. 计算数字

    目录

    1665. 计算数字描述样例 1:样例 2: 题解鸣谢

    1665. 计算数字

    描述

    给出一个十进制数num,现在你需要把它转成二进制数,并返回1的个数和位置。

    n <= 109

    样例 1:

    输入: 10 输出: [2,1,3] 解释: 10转成2进制为1010,总共有2个1,所以ouptput数组第一个是2。然后1的位置是第1个和第3个,所以后续两个数为1,3.

    样例 2:

    输入: 7 输出: [3,1,2,3] 解释: 7转成2进制为111,总共有3个1,所以output数组第一个是3。然后的位置是第1个、第2个和第3个,所以后续三个数为1,2,3.

    题解

    public class Solution { /** * @param num: the num * @return: the array subject to the description */ public int[] calculateNumber(int num) { // Write your code here. List<Integer> tRet = new ArrayList<>(); int bits = 1; while (num > 0) { if ((num & 1) == 1) { tRet.add(bits); } bits++; num >>= 1; } int[] ret = new int[tRet.size() + 1]; ret[0] = tRet.size(); for (int i = 1; i < ret.length; i++) { ret[i] = bits - tRet.get(tRet.size() - i); } return ret; } }

    原题链接点这里

    鸣谢

    非常感谢你愿意花时间阅读本文章,本人水平有限,如果有什么说的不对的地方,请指正。 欢迎各位留言讨论,希望小伙伴们都能每天进步一点点。

    Processed: 0.009, SQL: 8