1. Number of 1 bits
Write a function that takes an unsigned integer and returns the number of '1' bits it has (also known as the Hamming weight).
Hamming Weight (roughly saying) is number of 1's string, or the digits sum of binary representation.
Example: 11101 has hamming weight of 4
678012340567 has hamming weight of 10.
0000 has hamming weight of 0.
Code to solve this problem is:
def hammingWeight(self, n: int) -> int:
2. Subtract the Product and Sum of Digits of an Integer
The problem goes like this:
Given digits 123 is a integer. We have to first find the product of individual digits (i.e. 1 * 2 * 3) and then subtract to the sum of individual digits (i.e. 1 + 2 + 3). Which is 6 - 6 equals to zero.
234 -> 2 * 3 * 4 = 24
2 + 3 + 4 = 9
24 - 9 = 15
Code to solve this problem:
def subtractProductAndSum(self, n: int) -> int:
finalSum = 0
total = 
product = 1
for i in range (len(str(n))):
s = n % 10
n = n // 10
product = product * s
finalSum = finalSum + s
Note: This is my way of solving these problems. There are even more efficient and elegant way, feel free to share your ideas.