Medium
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:
Return the total sum of waviness for all numbers in the range [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.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.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 <= 105public class Solution {
private int countpeakValley(int num) {
int lastdigit = num % 10;
int waiviness = 0;
int prevcurrent = -1;
num = num / 10;
while (num > 0) {
if (prevcurrent == -1) {
prevcurrent = num % 10;
num = num / 10;
continue;
}
int currvalue = num % 10;
if ((prevcurrent > currvalue && prevcurrent > lastdigit)
|| (prevcurrent < currvalue && prevcurrent < lastdigit)) {
waiviness++;
}
lastdigit = prevcurrent;
prevcurrent = num % 10;
num = num / 10;
}
return waiviness;
}
public int totalWaviness(int num1, int num2) {
int ans = 0;
for (int i = num1; i <= num2; i++) {
int l = countpeakValley(i);
ans = ans + l;
}
return ans;
}
}