题目:

易老师购买了一盒饼干,盒子中一共有k块饼干,但是数字k有些数位变得模糊了,看不清楚数字具体是多少了。易老师需要你帮忙把这k块饼干平分给n个小朋友,易老师保证这盒饼干能平分给n个小朋友。现在你需要计算出k有多少种可能的数值
输入描述:

输入包括两行:

第一行为盒子上的数值k,模糊的数位用X表示,长度小于18(可能有多个模糊的数位)

第二行为小朋友的人数n

输出描述:

输出k可能的数值种数,保证至少为1

输入例子:

9999999999999X
3

输出例子:

4

分析:

要求任何人数的平均分配,用枚举法对每一个可能的数字进行整除。

算法代码:

int distributeCookies(string & cookies, int students)
{
    int numberOfProbobilities = 0;
    
    int numberOfCookies = transformCookies(cookies);
    
    int tempNumberOfCookies;
    
    for (int i = 0; i < 10; ++i) {
        tempNumberOfCookies = numberOfCookies + (i * flagOfPosition[0]);
        
        if (averageDistribute(tempNumberOfCookies, students)) {
            ++numberOfProbobilities;
        }
    }
    
    return numberOfProbobilities;
}

bool averageDistribute(int tempNumberOfCookies, int students)
{
    while (tempNumberOfCookies >= students) {
        tempNumberOfCookies -= students;
    }
    
    if (0 == tempNumberOfCookies) {
        return true;
    }
    else {
        return false;
    }
}

int transformCookies(string & cookies)
{
    int numberOfCookies = 0;
    int n = (int)cookies.size();
    
    for (int i = 0; i < n; ++i) {
        if ('X' == cookies[i]) {
            flagOfPosition.push_back(pow(10, n-1-i));
        }
        else {
            numberOfCookies += (((int)cookies[i] - 48) * pow(10, n-1-i));
        }
    }
    
    return numberOfCookies;
}

测试代码:

//
//  main.cpp
//  distributeCookies
//
//  Created by Jiajie Zhuo on 2017/7/3.
//  Copyright © 2017年 Jiajie Zhuo. All rights reserved.
//

#include <iostream>
#include <cmath>
#include <string>
#include <vector>

using namespace std;

vector<int> flagOfPosition;

int distributeCookies(string & cookies, int students);
int transformCookies(string & cookies);
bool averageDistribute(int tempNumberOfCookies, int students);

int main(int argc, const char * argv[]) {
    string cookies;
    cout << "Please enter the cookies: ";
    cin >> cookies;
    
    int students;
    cout << "Please enter the students: ";
    cin >> students;
    
    cout << "The probobilities of number is " << distributeCookies(cookies, students) << endl;
    
    return 0;
}

总结:

枚举法的效率很低,但是要求每一个人数,只能这样求解。