一、原题
原题链接 Simple Fun #6: Is Infinite Process?
Instructions
Task
给定整数 和 ,确定以下伪代码是否导致无限循环ab
while (a !== b){
a++
b--
}
Assume that the program is executed on a virtual machine which can store arbitrary long numbers and execute forever.
Example
For a = 2 and b = 6, the output should be
isInfiniteProcess(a, b) = false
(or equivalent in PHP)
For a = 2 and b = 3, the output should be
isInfiniteProcess(a, b) = true
(or equivalent in PHP)
Input/Output
[input]
integera
Constraints: 0 ≤ a ≤ 100.
[input]
integerb
Constraints: 0 ≤ b ≤ 100.
[output]
a boolean value
true if the pseudocode will never stop, false otherwise.
二、解题
1、读题
用bool is_infinite_process(unsigned a, unsigned b)判断给定的a、b在传入下面循环是否会发生死循环。 若会发生,bool is_infinite_process(unsigned a, unsigned b)返回1,否则返回0。
while (a !== b){ a++ b-- } |
2、分析
while (a !== b){ a++ b-- } |
上面循环体只有在a==b时才会终止循环,则分情况讨论:
1)a>b时,由于a++,b--,从而不会出现a==b,此时一定会死循环,返回1
if(a>b){
return 1;//是死循环
}
2)a==b时,循环体直接没法进行,不会死循环,返回0
else if(a==b){
return 0;//不是死循环
}
3)a<b时,会发现3,5会不会死循环;3,4会死循环。其规律为:
(1)a、b做差,结果为奇数,会死循环
(2) a、b做差,结果为偶数,会死循环
else{
if((b-a)%2==0){
return 0;
} else return 1;
}
3、Myway
#include <stdbool.h>
bool is_infinite_process(unsigned a, unsigned b) {
// <---- hajime!
if(a>b){
return 1;//是死循环
}
else if(a==b){
return 0;//不是死循环
}
else{
if((b-a)%2==0){
return 0;
} else return 1;
}
}
三、总结
1、bool
参考链接 C语言的布尔类型(_Bool)
1)自己定义的“仿布尔型”
/* 第一种方法 */
#define TRUE 1
#define FALSE 0
/* 第二种方法 */
enum bool{false, true};
2) 可以简单的使用 _Bool 来定义布尔型变量。_Bool类型长度为1,只能取值范围为0或1。将任意非零值赋值给_Bool类型,都会先转换为1,表示真。将零值赋值给_Bool类型,结果为0,表示假。
#include <stdio.h>
#include <stdlib.h>
int main(){
_Bool a = 1;
_Bool b = 2; /* 使用非零值,b的值为1 */
_Bool c = 0;
_Bool d = -1; /* 使用非零值,d的值为1 */
printf("a==%d, /n", a);
printf("b==%d, /n", b);
printf("c==%d, /n", c);
printf("d==%d, /n", d);
printf("sizeof(_Bool) == %d /n", sizeof(_Bool));
system("pause");
return EXIT_SUCCESS;
}