2022.12.05 PM 09:00 by CBJ
來源 : https://zerojudge.tw/ShowProblem?problemid=a149 出題者 : 雄中公假社 標籤 : 字元處理、算術運算、遞迴 難易度 : 1
解題想法 : 本題主要實作的點在於,將「字元」轉成「整數」。 C/C++ 可運用字元相減(ascii相減)的方式來求得「數字」的「數值」,方法為 (數字字元)-'0'。 (例如'9'-'0' = ascii('9')-ascii('0') = 57-48 = 9 ) Python 則可直接使用 int() 達成。 ※注意 : 相乘之前的答案要初始為1(而不是0),否則答案始終為0。 ※此題亦可使用遞迴解,詳可見程式碼中的 C recursive 部分
//C language
#include<stdio.h>
#include<string.h> //strlen()
int to_int(char c){
return c-'0';
}
int main(){
int T;
scanf("%d",&T);
while(T--){
char s[10];
scanf("%s",s);
int ans=1;
for(int i=0;i<strlen(s);i++){
ans*=to_int(s[i]);
}
printf("%d\n",ans);
}
return 0;
}
//C recursive
#include<stdio.h>
#include<string.h>
char a[10];
int to_int(char c){
return c-'0';
}
int f(int R){ //求出a[0]~a[R](不包含)的乘積
if(R==1) return to_int(a[0]);
return f(R-1) * to_int(a[R-1]);
}
int main(){
int n;
scanf("%d",&n);
while(n--){
scanf("%s",a);
printf("%d\n",f(strlen(a)));
}
return 0;
}


//C++ language
#include<iostream>
using namespace std;
int to_int(char c){
return c-'0';
}
int main(){
int T;
cin>>T;
while(T--){
string s;
cin>>s;
int ans=1;
for(char c:s){
ans*=to_int(c);
}
cout<<ans<<"\n";
}
return 0;
}

## Python language
T=int(input())
for i in range(T):
ans=1
for x in input():
ans*=int(x)
print(ans)
