991. Broken Calculator
Имеется неисправный калькулятор, на экране которого изначально отображается 정수 startValue. За одну операцию можно:
Умножить number на экране на 2, или
Вычесть 1 из числа на экране.
given два целых числа startValue и target. return минимальное количество операций, необходимых для отображения target на калькуляторе.
예제
Input: startValue = 2, target = 3
Output: 2
Explanation: Use double operation and then decrement operation {2 -> 4 -> 3}.
C# 해법
매칭됨/원본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++ 해법
자동 초안, 제출 전 검토#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 해법
매칭됨/원본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 해법
매칭됨/원본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 해법
매칭됨/원본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 해법
매칭됨/원본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
활성 채용 with overlapping task tags are 표시됨.