0
1

【C++】AtCoderで学んだ超基本的アルゴリズムの備忘録(随時更新)

Last updated at Posted at 2024-08-04
切り上げ
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;
}
0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1