Azeezah
BAN USER
Comments (2)
Reputation 0
Page:
1
Comment hidden because of low score. Click to expand.
Comment hidden because of low score. Click to expand.
0
of 0 vote
I'm going to assume that the numbers are in base 10 and that the digits are counted independently - i.e. 22 counts as two 2's.
This solution iteratively takes the most significant digits, converts them into their own integer, and adds that to the total. Each of these numbers represent the number of 2's in the following decimal place. For example, in the number 540, the number 54 is the number of 2's in the ones place. We'll also add 1 depending on whether the digit in the following decimal place is greater than or equal to 2.
def count2s(n):
n = '0' + str(n)
c = len(n)
total = 0
for i in range(1, c):
total += int(n[0:i]) + (int(n[i])>=2)
return total
Page:
1
CareerCup is the world's biggest and best source for software engineering interview preparation. See all our resources.
- Azeezah May 15, 2016