TGViewer
Java | LeetCode Java | LeetCode @easy_java_task · 6.43K subscribers
Post #1788 547
Задача: 1404. Number of Steps to Reduce a Number in Binary Representation to One
Сложность: medium

Дано бинарное представление целого числа в виде строки s. Верните количество шагов, необходимых для его сокращения до 1 по следующим правилам:
Если текущее число четное, его нужно разделить на 2.
Если текущее число нечетное, нужно прибавить к нему 1.
Гарантируется, что для всех тестовых случаев всегда можно достичь единицы.

Пример:
Input: s = "1101"
Output: 6
Explanation: "1101" corressponds to number 13 in their decimal representation.
Step 1) 13 is odd, add 1 and obtain 14.
Step 2) 14 is even, divide by 2 and obtain 7.
Step 3) 7 is odd, add 1 and obtain 8.
Step 4) 8 is even, divide by 2 and obtain 4.
Step 5) 4 is even, divide by 2 and obtain 2.
Step 6) 2 is even, divide by 2 and obtain 1.


👨‍💻 Алгоритм:

1⃣Инициализируйте переменную operations значением 0.

2⃣Повторяйте операции, пока длина строки s больше 1:
Если последний бит строки s равен 0, это означает, что число четное; примените операцию деления на 2, удалив последний бит.
В противном случае это означает, что число, представленное строкой, нечетное; добавьте 1 к числу, изменив строку, чтобы выполнить эту операцию.

3⃣Верните количество операций.

😎 Решение:
class Solution {

private void divideByTwo(StringBuilder s) {
s.deleteCharAt(s.length() - 1);
}

private void addOne(StringBuilder s) {
int i = s.length() - 1;

while (i >= 0 && s.charAt(i) != '0') {
s.setCharAt(i, '0');
i--;
}

if (i < 0) {
s.insert(0, '1');
} else {
s.setCharAt(i, '1');
}
}

public int numSteps(String s) {
StringBuilder str = new StringBuilder(s);

int operations = 0;
while (str.length() > 1) {
int N = str.length();

if (str.charAt(N - 1) == '0') {
divideByTwo(str);
} else {
addOne(str);
}

operations++;
}

return operations;
}
}


Ставь 👍 и забирай 📚 Базу знаний
More from @easy_java_task
  1. Oct 16, 2026Post #2300
  2. Oct 15, 2026Задача: 229. Majority Element II Сложность: medium Дан массив целых чисел размера n, найди…
  3. Oct 14, 2026Post #2298
  4. Oct 14, 2026Задача: 1332. Remove Palindromic Subsequences Сложность: easy Вам дана строка s, состоящая…
  5. Oct 13, 2026Задача: 1120. Maximum Average Subtree Сложность: medium Дан корень бинарного дерева. Верни…
  6. Oct 12, 2026Задача: 1413. Minimum Value to Get Positive Step by Step Sum Сложность: easy Дан массив це…
Threads Profile ViewerView any public Threads profile without an account.Open ThreadLook →Writing with AI? Make it sound human.Metric37 rewrites AI drafts so they read naturally. Free AI detector, 1,500 words free.Try Metric37 →