Description
You are given two integers num1 and num2 representing an inclusive range [num1, num2].
The waviness of a number is defined as the total count of its peaks and valleys:
- A digit is a peak if it is strictly greater than both of its immediate neighbors.
- A digit is a valley if it is strictly less than both of its immediate neighbors.
- The first and last digits of a number cannot be peaks or valleys.
- Any number with fewer than 3 digits has a waviness of 0.
[num1, num2].
Example 1:
Input: num1 = 120, num2 = 130
Output: 3
Explanation:
In the range[120, 130]:
120: middle digit 2 is a peak, waviness = 1.121: middle digit 2 is a peak, waviness = 1.130: middle digit 3 is a peak, waviness = 1.- All other numbers in the range have a waviness of 0.
Thus, total waviness is 1 + 1 + 1 = 3.
Example 2:
Input: num1 = 198, num2 = 202
Output: 3
Explanation:
In the range[198, 202]:
198: middle digit 9 is a peak, waviness = 1.201: middle digit 0 is a valley, waviness = 1.202: middle digit 0 is a valley, waviness = 1.- All other numbers in the range have a waviness of 0.
Thus, total waviness is 1 + 1 + 1 = 3.
Example 3:
Input: num1 = 4848, num2 = 4848
Output: 2
Explanation:
Number 4848: the second digit 8 is a peak, and the third digit 4 is a valley, giving a waviness of 2.
Constraints:
1 <= num1 <= num2 <= 105
Solutions
This code calculates a total "waviness" score for all whole numbers within a given range from num1 to num2 by counting how many times their digits form a "zigzag" or wave-like pattern. To achieve this, the main function loops through every number in the range and calls a helper function that analyzes each number's digits from right to left; this helper looks at every group of three consecutive digits and awards a point if the middle digit is either a "peak" (strictly larger than both of its neighbors, like 1-5-2) or a "valley" (strictly smaller than both of its neighbors, like 8-3-6). Finally, the code sums up these individual wave counts across the entire range of numbers and returns the grand total.
/**
* @param {number} num1
* @param {number} num2
* @return {number}
*/
var totalWaviness = function(num1, num2) {
let res = 0;
for (let i = num1; i <= num2; i++) {
res += calcWaviness(i);
}
return res;
};
const calcWaviness = (num) => {
if (num < 100) {
return 0;
}
let res = 0;
let last2 = undefined;
let last1 = undefined;
while (num > 0) {
const rem = num % 10;
if (last1 !== undefined &&
last2 !== undefined && (
(rem > last1 && last1 < last2) ||
(rem < last1 && last1 > last2)
)
) {
res++;
}
last2 = last1;
last1 = rem;
num = Math.floor(num / 10);
}
return res;
};