September 24Easy
Smallest index with digit sum equal to index
- Array
- Math
Problem
You are given an integer array nums.
Return the smallest index i such that the sum of the digits of nums[i] is equal to i.
If no such index exists, return -1.
Solution
def get_sum(n):
res = 0
while n > 0:
res += n%10
n //= 10
return res
class Solution:
def smallestIndex(self, nums: List[int]) -> int:
for i in range(len(nums)):
if i == get_sum(nums[i]):
return i
return -1