и посмотреть медиа
Golang | LeetCode
и посмотреть медиа
LeetCode tasks in Golang. Solutions with code and explanations.
LeetCode tasks in Golang. Solutions with code and explanations.
AI bot for text-to-speech and voice cloning in Telegram. Create audio using neural network quickly and easily.
Channel with solutions to popular LeetCode tasks in Go. Focus on optimized algorithms, efficient memory usage, and idiomatic code. Helps prepare for technical interviews in companies that use Golang.
Задача: 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⃣Верните количество операций. 😎 Решение: func numSteps(s string) int { str := []byte(s) operations := 0 for len(str) > 1 { if str[len(str)-1] == '0' { str = str[:len(str)-1] } else { i := len(str) - 1 for i >= 0 && str[i] == '1' { str[i] = '0' i-- } if i < 0 { str = append([]byte{'1'}, str...) } else { str[i] = '1' } } operations++ } return operations } Ставь 👍 и забирай 📚 Базу знаний
Открыть канал и посмотреть медиаOnly registered users can share their opinion.
Be the first to share your impression of this resource!