面试题44:扑克牌的顺子

来源:互联网 发布:淘宝店铺整体托管 编辑:程序博客网 时间:2024/05/16 01:07

题目:从扑克牌中随机抽5张牌,判断是不是一个顺子,即这5张牌是不是连续的。2-10为数字本身,A为1,J为11,Q为12,K为13,而大小王可以看成任意数字。

//"poker.h"#include <iostream>using std::cout;using std::endl;using std::ends;//从小到大排序void bubble_sort(int a[], int n){    for (int i = 0; i < n; i++){        for (int j = 1; j < n - i; j++){            if (a[j - 1]>a[j]){                int tmp = a[j - 1];                a[j - 1] = a[j];                a[j] = tmp;            }        }    }}bool is_sequence(int a[],int length){    //4*[1,13],2*0    if (length == NULL || length < 1){        return false;    }    bubble_sort(a, length);    /*for (int i = 0; i < length; i++){        cout << a[i] << ends;    }    cout << endl;*/    int cnt_zero = 0;    /*for (int i = 0; i < length; i++){        if (a[i] == 0){            cnt_zero++;        }    }*/    for (int i = 0; i < length && a[i]==0; i++){            cnt_zero++;    }    int small = cnt_zero;    int big = small + 1;    int cnt_gap = 0;    while (big < length){        if ((a[big] - a[small]) == 0){            //有对子,则不为顺子            return false;        }        cnt_gap = cnt_gap + a[big] - a[small]-1;        small++;        big++;    }    /*if (cnt_gap > cnt_zero){        return false;        }        else{        return true;        }        return true;*/    return (cnt_gap > cnt_zero) ? false : true;}

测试:

void test(){    int poker[5] = { 0, 5, 3, 4, 1 };    bool b = is_sequence(poker, 5);    if (b){        cout << "true" << endl;    }    else{        cout << "false" << endl;    }}
0 0
原创粉丝点击