zoukankan      html  css  js  c++  java
  • leetcode 1342. Number of Steps to Reduce a Number to Zero

    Given a non-negative integer num, return the number of steps to reduce it to zero. 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
    

    Constraints:

    • 0 <= num <= 10^6

    题目大意:给定一个非负整数num,返回将其变为0的步数。如果当前的数是偶数,将其除2,否则将其减去1.

    思路:直接模拟,为了提高效率,除2用位运算。

    C++代码1:

     1 class Solution {
     2 public:
     3     int numberOfSteps (int num) {
     4         int cnt = 0;
     5         while (num != 0) {
     6             if (num & 1) //为奇数
     7                 num--;
     8             else
     9                 num >>= 1;
    10             cnt++;
    11         }
    12         return cnt;
    13     }
    14 };

    C++代码二:

    一般条件下,如果一个数是奇数,我们将其减去1后,下一步肯定除2,(如(5 - 1)/2=2,用了两步),而利用位运算,可以直接右移一位,会产生两步的效果:5 >> 1 = 2.

    只要整数num一直减小,在变成0之前,肯定会变成1. 当数为1时,步数会多算1.

    class Solution {
    public:
        int numberOfSteps (int num) {
            int cnt = 0;
            while (num != 0) {
                cnt += (num & 1) ? 2 : 1;
                num >>= 1;
            }
            return cnt - 1;
        }
    };

     python3代码:

    1 class Solution:
    2     def numberOfSteps (self, num: int) -> int:
    3         cnt = 0
    4         while num != 0: 
    5             num, cnt = num - 1 if num % 2 else num // 2, cnt + 1
    6         return cnt
  • 相关阅读:
    chrome 等浏览器不支持本地ajax请求的问题
    3:1 类型转换
    WebService-WSDL简单介绍
    WebService—CXF整合Spring实现接口发布和调用过程
    WebService—CXF—实现接口发布和客户端调用
    WebService—规范介绍和几种实现WebService的框架介绍
    (转)c# 扩展方法
    (转)C# Textbox的ImeMode取值对中文输入法的影响
    (转)Nandflash读写
    (转+整理)Nandflash存储
  • 原文地址:https://www.cnblogs.com/qinduanyinghua/p/12299781.html
Copyright © 2011-2022 走看看