1.前提
其实这个问题和二分挺像的,需要理出模板来。和二分不同的是,这个不能死板就按着一个模板来,先向前还是先判断,都是会用到的。
先向前和先处理区别在于:
- 先向前的话,要考虑终点的处理,到底终点要不要;
- 先处理的话,要考虑起点的处理,到底起点要不要;
有一个相似但不相同的问题,就是while与do…while,这两个其实只是单纯的循环控制,而且费点功夫也可以相互转化。为什么要设计两个?查阅资料之后,我的观点是:
- 实现两个也不难,不费什么功夫;
- 历史包袱问题,汇编里就是do…while形式的;
这个问题和本文的问题其实是不怎么相关的。
2.向前再处理
定时处理,一般就是先向前再处理比较适合,起点一般是不要的,而终点是需要的。
while(true)
{
//second
timeWheel[0] = (timeWheel[0] + 1) % 60;
//minute
if(0 == timeWheel[0])
{
cout << "minute: " << timeWheel[1] << endl;
timeWheel[1] = (timeWheel[1] + 1) % 60;
//hours
if(0 == timeWheel[1])
{
cout << "hours: " << timeWheel[2] << endl;
timeWheel[2] = (timeWheel[2] + 1) % 60;
break;
}
}
}
3.处理再向前
感觉和for比较类似,for应该是天然的处理再向前。
while(true)
{
//minute
if(0 == timeWheel[0])
{
cout << "minute: " << timeWheel[1] << endl;
//hours
if(0 == timeWheel[1])
{
cout << "hours: " << timeWheel[2] << endl;
timeWheel[2] = (timeWheel[2] + 1) % 60;
break;
}
timeWheel[1] = (timeWheel[1] + 1) % 60;
}
//second
timeWheel[0] = (timeWheel[0] + 1) % 60;
}