Description
Smallest Index With Digit Sum Equal to Index
EasyYou 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.
Example 1:
Input: nums = [1,3,2]
Output: 2
Explanation:
- For
nums[2] = 2, the sum of digits is 2, which is equal to indexi = 2. Thus, the output is 2.
Example 2:
Input: nums = [1,10,11]
Output: 1
Explanation:
- For
nums[1] = 10, the sum of digits is1 + 0 = 1, which is equal to indexi = 1. - For
nums[2] = 11, the sum of digits is1 + 1 = 2, which is equal to indexi = 2. - Since index 1 is the smallest, the output is 1.
Example 3:
Input: nums = [1,2,3]
Output: -1
Explanation:
- Since no index satisfies the condition, the output is -1.
Constraints:
1 <= nums.length <= 1000 <= nums[i] <= 1000
Solutions
Trivial.
Language: javascript()DONE
CPU Performance64.23%
x
Memory Performance97.30%
x
/**
* @param {number[]} nums
* @return {number}
*/
var smallestIndex = function(nums) {
for (let i = 0; i < nums.length; i++) {
let num = nums[i];
let sum = 0;
while (num > 0) {
sum += num % 10;
num = Math.floor(num / 10);
}
if (sum === i) {
return i;
}
}
return -1;
};