標籤:mystra 編程演算法 撲克牌的順子 代碼 c
撲克牌的順子 代碼(C)
本文地址: http://blog.csdn.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