- 在区间范围内统计奇数数目
给你两个非负整数 low 和 high 。请你返回 low 和 high 之间(包括二者)奇数的数目。
//方案一输出超限.这种方法效率不高O(n);
class Solution {
public int countOdds(int low, int high) {
int count=0;
for(int i=low;i<=high;i++){
if(i%2!=0){
count++;
}
}
return count;
}
}
//方案二 正确.O(1);该种方法通过数学规律总结
class Solution {
public int countOdds(int low, int high) {
int len = high - low + 1; //范围之内的总个数
if(low%2!=0 && high%2!=0) return (len+1)/2; //如果给定范围的两端均为奇数.则输出这个结果.
else return len/2;//其他结果输出该结果.
}
}
//想要理解该思路.请动笔找下规律