Input: nums =[1,10,11]Output: 1Explanation:
* For `nums[1] = 10`, the sum of digits is`1 + 0 = 1`, which is equal to index `i = 1`.* For `nums[2] = 11`, the sum of digits is`1 + 1 = 2`, which is equal to index `i = 2`.* Since index 1is the smallest, the output is1.
#include<vector>usingnamespace std;
classSolution {
public:int smallestIndex(vector<int>& nums) {
for (int i =0; i < nums.size(); ++i) {
int x = nums[i], s =0;
while (x) { s += x %10; x /=10; }
if (s == i) return i;
}
return-1;
}
};
1
2
3
4
5
6
7
8
9
10
classSolution {
publicintsmallestIndex(int[] nums) {
for (int i = 0; i < nums.length; ++i) {
int x = nums[i], s = 0;
while (x > 0) { s += x % 10; x /= 10; }
if (s == i) return i;
}
return-1;
}
}
1
2
3
4
5
6
classSolution:
defsmallestIndex(self, nums):
for i, x in enumerate(nums):
if sum(map(int, str(x))) == i:
return i
return-1