991. Broken Calculator

LeetCode medium original: C# #backtracking #csharp #leetcode #medium
Le texte du problème est traduit du russe pour la langue sélectionnée. Le code reste inchangé.

Имеется неисправный калькулятор, на экране которого изначально отображается entier startValue. За одну операцию можно:

Умножить number на экране на 2, или

Вычесть 1 из числа на экране.

given два целых числа startValue и target. return минимальное количество операций, необходимых для отображения target на калькуляторе.

Exemple

Input: startValue = 2, target = 3

Output: 2

Explanation: Use double operation and then decrement operation {2 -> 4 -> 3}.

C# solution

correspondant/original
public class Solution {
    public int BrokenCalc(int startValue, int target) {
        int operations = 0;
        
        while (target > startValue) {
            operations++;
            if (target % 2 == 0) {
                target /= 2;
            } else {
                target += 1;
            }
        }
        
        return operations + (startValue - target);
    }
}

C++ solution

brouillon automatique, à relire avant soumission
#include <bits/stdc++.h>
using namespace std;

// Auto-generated C++ draft from the C# solution. Review containers, LINQ and helper types before submit.
class Solution {
public:
    public int BrokenCalc(int startValue, int target) {
        int operations = 0;
        
        while (target > startValue) {
            operations++;
            if (target % 2 == 0) {
                target /= 2;
            } else {
                target += 1;
            }
        }
        
        return operations + (startValue - target);
    }
}

Java solution

correspondant/original
public class Solution {
    public int brokenCalc(int startValue, int target) {
        int operations = 0;
        
        while (target > startValue) {
            operations++;
            if (target % 2 == 0) {
                target /= 2;
            } else {
                target += 1;
            }
        }
        
        return operations + (startValue - target);
    }
}

JavaScript solution

correspondant/original
var brokenCalc = function(startValue, target) {
    let operations = 0;
    
    while (target > startValue) {
        operations++;
        if (target % 2 === 0) {
            target /= 2;
        } else {
            target += 1;
        }
    }
    
    return operations + (startValue - target);
};

Python solution

correspondant/original
class Solution:
    def brokenCalc(self, startValue: int, target: int) -> int:
        operations = 0
        
        while target > startValue:
            operations += 1
            if target % 2 == 0:
                target //= 2
            else:
                target += 1
                
        return operations + (startValue - target)

Go solution

correspondant/original
func brokenCalc(startValue int, target int) int {
    operations := 0
    
    for target > startValue {
        operations++
        if target % 2 == 0 {
            target /= 2
        } else {
            target++
        }
    }
    
    return operations + (startValue - target)
}

Algorithm

Обратный путь:

Если target больше startValue, то попытайтесь уменьшить target, чтобы привести его к startValue.

Если target четный, разделите его на 2, иначе прибавьте 1.

Подсчет операций:

Повторяйте шаги, пока target не станет меньше или равен startValue.

После этого вычитайте из startValue оставшееся значение target.

Возврат результата:

Возвращайте суммарное количество выполненных операций.

😎

Vacancies for this task

offres actives with overlapping task tags are affichés.

Toutes les offres
Il n'y a pas encore d'offres actives.