栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

1342 + 数学运算 + java

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

1342 + 数学运算 + java

题目描述

Given an integer num, return the number of steps to reduce it to zero.

In one step, if the current number is even, you have to divide it by 2, otherwise, you have to subtract 1 from it.

Example 1:

Input: num = 14
Output: 6
Explanation:
Step 1) 14 is even; divide by 2 and obtain 7.
Step 2) 7 is odd; subtract 1 and obtain 6.
Step 3) 6 is even; divide by 2 and obtain 3.
Step 4) 3 is odd; subtract 1 and obtain 2.
Step 5) 2 is even; divide by 2 and obtain 1.
Step 6) 1 is odd; subtract 1 and obtain 0.
Example 2:

Input: num = 8
Output: 4
Explanation:
Step 1) 8 is even; divide by 2 and obtain 4.
Step 2) 4 is even; divide by 2 and obtain 2.
Step 3) 2 is even; divide by 2 and obtain 1.
Step 4) 1 is odd; subtract 1 and obtain 0.
Example 3:

Input: num = 123
Output: 12

给你一个非负整数 num ,请你返回将它变成 0 所需要的步数。 如果当前数字是偶数,你需要把它除以 2 ;否则,减去 1 。

示例 1:

输入:num = 14
输出:6
解释:
步骤 1) 14 是偶数,除以 2 得到 7 。
步骤 2) 7 是奇数,减 1 得到 6 。
步骤 3) 6 是偶数,除以 2 得到 3 。
步骤 4) 3 是奇数,减 1 得到 2 。
步骤 5) 2 是偶数,除以 2 得到 1 。
步骤 6) 1 是奇数,减 1 得到 0 。
示例 2:

输入:num = 8
输出:4
解释:
步骤 1) 8 是偶数,除以 2 得到 4 。
步骤 2) 4 是偶数,除以 2 得到 2 。
步骤 3) 2 是偶数,除以 2 得到 1 。
步骤 4) 1 是奇数,减 1 得到 0 。
示例 3:

输入:num = 123
输出:12

思路

num 每次 减半
如果是偶数 减半,如果是奇数 -1
知道num变为零。

while 循环条件 num是否为零。

改进版
把判断奇数偶数从 num % 2 == 1
变为 num & 1 != 1
把num / 2
变为 num >> 1

代码
class Solution {
    
    // mathemetical operation
    public int numberOfSteps(int num) {
        int res = 0;
        // loop while a number is greater than zero
        while (num != 0){ // keep doing this, until we get zero
            if (num % 2 == 0){ // condition check even num: num mod 2 is equal to 0
                num = num / 2;
            } else{
                num = num - 1;
            }
            res++; // take steps to count the numbers
        }
        return res; // reach to number 0 from xx
    }
    
}

// log(n)
// o(1)
class Solution {
    public int numberOfSteps(int num) {
        int count = 0;
        while ( num != 0){
            if ((num & 1) != 1){
                num = num >> 1;
            } else{
                num--;
            }
            count++;
        }

        return count;
    }
}
Reference

https://leetcode.cn/problems/number-of-steps-to-reduce-a-number-to-zero

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/936749.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号