密码穷举次数

假设现在有一段长度为 n 的密码字符,由 0 ~ 9 和 小写字母 a ~ f 组成 。

输入一段密码,求计算穷举该密码所需的次数。 ( a ~ f 请将其转化为 10 ~ 15 )

如: 

输入 : 00    输出 :1

输入 : 01    输出 :2

输入 : 1a    输出 :27

 

#include <iostream>
#include <string>

using namespace std;
long countall(string &s);
long count(string &s,int m,int n);
int main()
{
    
    string s;
    cin >> s;
    cout <<"总数是"<< countall(s)<<endl;
    return 0;
}

long countall(string &s)
{
    long sum = 0;
    sum =  count(s,0,s.length());
    return sum;
}
long count(string &s,int m,int n)
{
    /*获取s的第m位*/
    char c = s[m];
    if(c >= '0' && c <= '9')
        c -= '0';
    else
        if(c >= 'a' && c <= 'f')
            c = c - 'a' + 10;

    /*到达最低位,返回其值+1*/
    if(m == n - 1)
        return c + 1;
    else
    {
        long sum = 0;
        while(c--)
            sum += pow(16,n - m - 1);
        
        return sum + count(s,m+1,n);
    }
}

 

posted @ 2013-12-30 02:05  迷路君的博客  Views(721)  Comments(0Edit  收藏  举报