A - Changing a Character
正解
# include<bits/stdc++.h>
using namespace std;
int main(){
int N,K; cin >> N >> K;
string S; cin >> S;
S[K-1]=tolower(S[K-1]);
cout << S;
}
B - YYMM or MMYY(もう一回)
正解
# include<bits/stdc++.h>
using namespace std;
int main(){
int S; cin >> S;
int L=S/100; //R=上2桁
int R=S%100; //L=下2桁
if (1<=L && L<=12){
if (1<=R && R<=12) cout << "AMBIGUOUS";
else cout << "MMYY";
}else{
if (1<=R && R<=12) cout << "YYMM";
else cout << "NA";
}
}
改善点(int型 or string型)
4桁の数字を入力する際にSを文字列として扱った。その際、どのような場合分けによって条件を満たせるか考えたが積んだ…
Sをint型として捉えると、簡単に上2桁と下2桁に分けられ、場合分けがしやすくなることは盲点だった
C - Dice and Coin
正解
# include<bits/stdc++.h>
using namespace std;
int main(){
int N,K; cin >> N >> K;
double sum=0;
int cnt=0;
for (double i=1; i<=N; i++){
int now=i;
while(now<K){
now=now*2;
cnt++;
}
sum+=(1.0/N)*pow(0.5,cnt);
cnt=0;
}
cout << fixed<< setprecision(12) <<sum<< endl;
}
自分の誤答
# include<bits/stdc++.h>
using namespace std;
int main(){
int N,K; cin >> N >> K;
double sum=0;
int cnt=0;
for (double i=1; i<=N; i++){
while(i<K){
i=i*2;
cnt++;
}
sum+=(1.0/N)*pow(0.5,cnt);
cnt=0;
}
cout << fixed<< setprecision(12) <<sum<< endl;
}
改善点(iの変化を止めたい&fixed << setprecision(12))
①iの値を1→2→3→....→Nとしたいのに、自分の誤答のプログラムではwhileのブロックでiが使われているので、そのブロックが終わったとき、iが2倍以上に変化して困る。
そんな時には、**新たな変数(now)でwhileブロックで処理すればiの値は変化しないので、問題なし!
②fixed << setprecision(12)**と打つことで、printf文で桁数を指定しなくても済む!