문제풀이 2021 01 25
2021.01.25 연습
- 사용언어 : java
class Solution {
public int numberOfSteps (int num) {
int count = 0;
while (num>0) {
if (num%2 == 0) {
num = num/2;
} else {
num--;
}
count++;
}
return count;
}
}
Runtime: 0 ms, faster than 100.00% of Java online submissions for Number of Steps to Reduce a Number to Zero. Memory Usage: 35.6 MB, less than 78.90% of Java online submissions for Number of Steps to Reduce a Number to Zero.
- 다른 코드 참고
//Method 1: Iterative
//T: O(n), S: O(1)
public int numberOfSteps (int num) {
int steps = 0;
while (num != 0) {
if ((num & 1) == 0)
num >>= 1;
else
num--;
steps++;
}
return steps;
}
//Method 2 Recursive
//T: O(n), S: O(n)
public int numberOfSteps(int num) {
return recurse(num, new int[1]);
}
public int recurse(int num, int[] steps) {
if (num == 0)
return steps[0];
steps[0]++;
return ((num & 1) == 0) ? recurse(num >> 1, steps) : recurse(num - 1, steps);
}
//Method 2 Recursive2
public int numberOfSteps (int num) {
if(num==0)return 0;
return 1 + numberOfSteps(num%2==0?num/2:num-1);
}