991. Broken Calculator

LeetCode medium original: C# #backtracking #csharp #leetcode #medium
Văn bản bài toán được dịch từ tiếng Nga theo ngôn ngữ giao diện. Mã không thay đổi.

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

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

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

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

Ví dụ

Input: startValue = 2, target = 3

Output: 2

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

C# lời giải

đã khớp/gố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++ lời giải

bản nháp tự động, xem lại trước khi gửi
#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 lời giải

đã khớp/gố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);
    }
}

JavaScript lời giải

đã khớp/gốc
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 lời giải

đã khớp/gốc
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 lời giải

đã khớp/gốc
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

việc làm đang hoạt động with overlapping task tags are đã hiển thị.

Tất cả việc làm
Chưa có việc làm đang hoạt động.