描述:
这两列数字,类似于电子表的“日”字形表示,每边分别需要用3、4个“*”表示,给你一个数字字符串,在单边需要m个“*”表示的情况下,这个数字需要多少“*”呢?
-
程序输入字符串和m
-
将结果输出即可
例如,输入473,答案为16
输入6934,答案为52
解题要点:日字型 具有对称性,找出横边与竖边的关系,即可容易得出
#include <iostream>
#include <cstring>
#include <vector>
#include <exception>
#include <time.h>
#include <math.h>
#include <stdlib.h>
using namespace std;
//定义数字的行数和列数
typedef struct{
int row;
float col;
}point;
//创建存储结构
void Buildvec(point *vec){
point temp;
for(int i=0; i<10; ++i){
switch(i){
case 0:
temp.row = 2; temp.col = 2; break;
case 1:
temp.row = 0; temp.col = 1; break;
case 2:
temp.row = 3; temp.col = 1; break;
case 3:
temp.row = 3; temp.col = 1; break;
case 4:
temp.row = 1; temp.col = 1.5; break;
case 5:
temp.row = 3; temp.col = 1; break;
case 6:
temp.row = 3; temp.col = 1.5; break;
case 7:
temp.row = 1; temp.col = 1; break;
case 8:
temp.row = 3; temp.col = 2; break;
case 9:
temp.row = 3;temp.col = 1.5; break;
}
vec[i] = temp;
}
}
//检查数字格式
bool ParseFormat(string str){
for(unsigned int i=0; i<str.length(); ++i)
if(str[i]<'0' || str[i]>'9')
return false;
return true;
}
//获取星型的总个数,rows为单行的星型个数,
int GetstarTotal(point *vec, string str, int rows){
if(NULL == vec || rows < 2) return 0;
int total = 0;
int cols = 2*rows - 1;
for(unsigned int i=0; i<str.length(); ++i){
int row = vec[str[i] - '0'].row;
float col = vec[str[i] - '0'].col;
total += row * rows + col * (cols - row);
}
return total;
}
int Random(int start, int end){
srand((unsigned int)time(NULL));
return rand()%(end-start+1) +start;
}
int main(){
string str;
int m = 2; //单行星型个数,m最小为2,一个星星没法组成数字
int couples = 0; //测试数据组数
cout<<Random(3,5)<<endl;
cout<<"Input your test couples:";
cin>>couples;
while(couples--){
point vec[10];
cin>>str>>m;
if(!ParseFormat(str)){
cout<<"格式错误"<<endl;
return 1;
}
Buildvec(vec);
cout<<GetstarTotal(vec, str, m)<<endl;
}
return 0;
}