Input: nums =[1,10,11]Output: 1Explanation:
For nums[1]=10, the sum of digits is1+0=1, which is equal to index i =1.For nums[2]=11, the sum of digits is1+1=2, which is equal to index i =2.Since index 1is the smallest, the output is1.
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;
}
};
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
7
8
9
10
11
12
13
14
classSolution {
funsmallestIndex(nums: IntArray): Int {
for (i in nums.indices) {
var x = nums[i]
var s = 0while (x > 0) {
s += x % 10 x /=10 }
if (s == i) return i
}
return -1 }
}
1
2
3
4
5
6
7
classSolution:
defsmallestIndex(self, nums: list[int]) -> int:
for i, v in enumerate(nums):
s = sum(int(d) for d in str(v))
if s == i:
return i
return-1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
impl Solution {
pubfnsmallest_index(nums: Vec<i32>) -> i32 {
for (i, &v) in nums.iter().enumerate() {
letmut x = v;
letmut s =0;
while x >0 {
s += x %10;
x /=10;
}
if s == i asi32 {
return i asi32;
}
}
-1 }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
classSolution {
smallestIndex(nums: number[]):number {
for (leti=0; i<nums.length; i++) {
letx=nums[i], s=0;
while (x>0) {
s+=x%10;
x= Math.floor(x/10);
}
if (s===i) returni;
}
return-1;
}
}