Skip to content

1342. Number of Steps to Reduce a Number to Zero 👍

  • Time: $O(1)$
  • Space: $O(1)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
class Solution {
 public:
  int numberOfSteps(unsigned num) {
    if (num == 0)
      return 0;
    const int subtractSteps = popcount(num);
    const int divideSteps = 31 - __builtin_clz(num);
    return subtractSteps + divideSteps;
  }
};
1
2
3
4
5
6
7
8
9
public class Solution {
  public int numberOfSteps(int num) {
    if (num == 0)
      return 0;
    final int subtractSteps = Integer.bitCount(num);
    final int divideSteps = 31 - Integer.numberOfLeadingZeros(num);
    return subtractSteps + divideSteps;
  }
}
1
2
3
4
5
6
7
class Solution:
  def numberOfSteps(self, num: int) -> int:
    if num == 0:
      return 0
    subtractSteps = num.bit_count()
    divideSteps = num.bit_length() - 1
    return subtractSteps + divideSteps