切り上げ
main.c
#include <bits/stdc++.h>
using namespace std;
int main() {
int a, b; cin >> a >> b;
cout << (a + b + 1) / 2 << endl;
}
k桁目の値
main.c
#include <bits/stdc++.h>
using namespace std;
int main() {
int n, k; cin >> n >> k;
cout << n / (int)pow(10, k - 1) % 10 << endl;
}
各桁の値の和
①再帰関数
main.c
#include <bits/stdc++.h>
using namespace std;
int sum_of_digits(int n) {
if (n < 10) return n;
return digit_sum(n / 10) + (n % 10);
}
int main() {
int n; cin >> n;
cout << sum_of_digits(n) << endl;
}
②while文
main.c
#include <bits/stdc++.h>
using namespace std;
int main() {
int n; cin >> n;
int sum = 0;
while(n) {
sum += n % 10;
n /= 10;
}
cout << sum << endl;
}
数値の回文の形成
main.c
#include <bits/stdc++.h>
using namespace std;
int reverse(int n, int rev) {
if (n == 0) return rev;
return reverse(n / 10, rev * 10 + n % 10);
}
int main() {
int n; cin >> n;
cout << reverse(n, 0) << endl;
}