扑克牌的顺子 代码(C)
本文地址: http://blog.****.net/caroline_wendy
题目: 从扑克牌中随机抽取5张牌, 推断是不是一个顺子, 即这5张牌是不是连续的.
2~10为数字本身, A为1, J为11, Q为12, K为13, 而大小王能够看成随意数字.
排序, 推断字符串之间的间隔数, 假设小于等于大小王的数量, 则是连续, 否则不是.
代码:
/*
* main.cpp
*
* Created on: 2014.7.12
* Author: spike
*/ #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h> using namespace std; int compare(const void* num1, const void* num2) {
return *(int*)num1-*(int*)num2;
} bool IsContinuous(int* numbers, int length) {
if (numbers == NULL || length < 1)
return false;
qsort(numbers, length, sizeof(int), compare);
int numberOfZero = 0;
int numberOfGap = 0;
for (int i=0; i<length&&numbers[i]==0; ++i)
++numberOfZero;
int small = numberOfZero;
int big = small+1;
while(big < length) {
if (numbers[small] == numbers[big])
return false;
numberOfGap += numbers[big] - numbers[small]-1;
small = big;
++big;
}
return (numberOfGap>numberOfZero) ? false : true;
} int main(void)
{
int numbers[] = {0, 3, 1, 4, 5};
bool result = IsContinuous(numbers, 5);
printf("result = %s\n", result ? "true" : "false");
return 0;
}
输出:
result = true