1342. Number of Steps to Reduce a Number to Zero

LeetCode easy original: C# #csharp #easy #leetcode
O texto da tarefa é traduzido do russo para o idioma selecionado. O código permanece sem alterações.

given inteiro num, вернуть количество шагов, необходимых для его сокращения до нуля.

На каждом шаге, если текущее number четное, его нужно разделить на 2, в противном случае, вы должны вычесть из него 1.

Exemplo:

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.

C# solução

correspondente/original
public int NumberOfSteps(int num) {
    int steps = 0;
    while (num != 0) {
        if (num % 2 == 0) {
            num /= 2;
        } else {
            num -= 1;
        }
        steps++;
    }
    return steps;
}

C++ solução

rascunho automático, revisar antes de enviar
#include <bits/stdc++.h>
using namespace std;

// Auto-generated C++ draft from the C# solution. Review containers, LINQ and helper types before submit.
public int NumberOfSteps(int num) {
    int steps = 0;
    while (num != 0) {
        if (num % 2 == 0) {
            num /= 2;
        } else {
            num -= 1;
        }
        steps++;
    }
    return steps;
}

Java solução

rascunho automático, revisar antes de enviar
import java.util.*;
import java.math.*;

// Auto-generated Java draft from the C# solution. Review API differences before LeetCode submit.
public int NumberOfSteps(int num) {
    int steps = 0;
    while (num != 0) {
        if (num % 2 == 0) {
            num /= 2;
        } else {
            num -= 1;
        }
        steps++;
    }
    return steps;
}

Python solução

correspondente/original
def numberOfSteps(num):
    steps = 0
    while num != 0:
        if num % 2 == 0:
            num //= 2
        else:
            num -= 1
        steps += 1
    return steps

Go solução

correspondente/original
func numberOfSteps(num int) int {
    steps := 0
    for num != 0 {
        if num % 2 == 0 {
            num /= 2
        } else {
            num--
        }
        steps++
    }
    return steps
}

Algorithm

1⃣На каждом шаге проверяйте, четное ли текущее number, используя оператор остатка от деления (%). Если number четное (number % 2 == 0), разделите его на 2.

2⃣Если number нечетное (number % 2 == 1), вычтите из него 1.

3⃣После выполнения каждого из этих действий увеличивайте счетчик шагов на 1, чтобы в конце вернуть его значение.

😎

Vacancies for this task

vagas ativas with overlapping task tags are mostradas.

Todas as vagas
Ainda não há vagas ativas.