-
Notifications
You must be signed in to change notification settings - Fork 15
Expand file tree
/
Copy pathsolution1.js
More file actions
45 lines (43 loc) · 790 Bytes
/
solution1.js
File metadata and controls
45 lines (43 loc) · 790 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
/**
* https://leetcode-cn.com/problems/number-of-steps-to-reduce-a-number-in-binary-representation-to-one/submissions/
*
*
* 将二进制表示减到 1 的步骤数
*
* Medium
*
* 60ms 100.00%
* 34.2mb 100.00%
*/
const numSteps = s => {
let arr = s.split('');
let step = 0;
while (arr.length !== 1) {
if (arr[arr.length - 1] === '0') {
arr.pop();
} else {
addOne(arr);
}
step++;
}
return step;
}
function addOne(arr) {
const maxIndex = arr.length - 1;
arr[maxIndex] = '0';
let flag = true;
for (let i = maxIndex - 1; i >= 0; i--) {
if (arr[i] === '1') {
arr[i] = '0';
flag = true;
} else {
arr[i] = '1';
flag = false;
break;
}
}
if (flag) {
arr.unshift('1');
}
return arr;
}