算法学习系列2.3

来源:互联网 发布:看太空的软件 编辑:程序博客网 时间:2024/06/04 00:30

均采用C++通过。


  • 1、求摩尔质量,元素只含C:12.01 || ,H:1.008 ,O:16.00 ,N:,如输入C6H50H给出结果:94.108g/mol
C H O N 12.01 1.008 16.00 14.01

#define maxn 100005

int ans[maxn];void  digit_generator(){    int T,n;    for(int i= 0;i<100005;i++) {        ans[i] = 0;    }    for(int m= 1;m<maxn;m++){        int x= m , y=m;        //将m作为y的生成元,这儿提取m的各个位数然后相加        while(x>0){            y+=x%10;            x/=10;        }        if(ans[y]==0||m<ans[y]) ans[y] = m;    }    scanf("%d",&T);//循环次数    while(T--){        scanf("%d",&n);        printf("%d\n",ans[n]);    }}

  • 2、计算周期字符串的最小周期,字符个数<80

    void count_T(){

    char s[85];int T=0;int flag=0;int i=0,j = 1;scanf("%s",s);for(;j<strlen(s);j++){    if(s[i]==s[j]) {        T++;        i++;        if(flag==0){            flag=j;        }        if(flag ==i)break;    }    else {        if(flag>i) j--;        i=0;        T=0;        flag=0;    }}printf("%d\n",T);

    }


  • 3、计算1、2、3、4···10000中各个数出现的次数,如123中1出现的次数为1,2出现的次数为1,3出现的次数为1。

    void digit_counting(){

    int copy;int count[10];int number;for(int j=0;j<10;j++)    count[j]=0;for(int i = 1;i<=10000;i++){    copy = i;    while(copy>0){        number = copy%10;        count[number]++;        copy/=10;    }}for(int j=0;j<10;j++)    printf("%d\t",count[j]);

    }