Lilah有一個字串s, s由小寫的英文字母組成,她會一直不斷地重複它。
給定一個整數n,找到並印出前n個字母中,字母'a'所出現的次數。
輸入:
第一行包含一個字串s,
第二行是整數n。
限制:
1<=|s|<=100
1<=n<=10的12次方
這當中有25%的測資是n<=10的6次方
輸出:
印出一個整數,用以代表在前n個字母裡面a出現幾次。
解題:
我們分成2種case:
case 1: s的長度為1
這種情況下要是s剛好是a的話,
那答案就是n,否則就是0。
case 2: s的長度大於1
我們可以計算在計到n時,總共經過了幾次s,
答案=(經過次數)*(s所含a的個數)+(最後餘數所含的a的個數)
請留意code內的方法,可以讓我們只遍歷一遍s就算完全部。
Code:
#include <math.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <assert.h>
#include <limits.h>
#include <stdbool.h>
int main(){
char* s = (char *)malloc(512000 * sizeof(char));
scanf("%s",s);
long n;
scanf("%ld",&n);
if(strlen(s) == 1)
{
if(s[0] == 'a')
printf("%ld", n);
else
printf("0");
}else {
int leng = strlen(s);
long quotient = n / leng, remainder = n % leng;
int a_total = 0, a_remain = 0, i = 0;
while(i < remainder){
if(s[i] == 'a'){
a_total++;
a_remain++;
}
i++;
}
while(i < leng){
if(s[i] == 'a'){
a_total++;
}
i++;
}
printf("%ld", quotient * a_total + a_remain);
}
return 0;
}
沒有留言:
張貼留言