LoginSignup
1
0

More than 1 year has passed since last update.

AtCoderログ:0047 - ABC 090 B

Posted at

問題

問題文

$A$ 以上 $B$ 以下の整数のうち、回文数となるものの個数を求めてください。 ただし、回文数とは、先頭に $0$ をつけない $10$ 進表記を文字列として見たとき、前から読んでも後ろから読んでも同じ文字列となるような正の整数のことを指します。

制約

・$10000 \le A \le B \le 99999$
・入力はすべて整数である

収録されている問題セット

回答

回答1 (AC)

回文数 (Palindromic Numbers) に関する問題です。整数 i を a 以上 b 以下の範囲で変化させ、i が回文数かどうかをチェックし、回文数である場合にはカウンター answer の値を1ずつ増やしていけば良いでしょう。整数 i が回文数かどうかのチェックは一般には面倒ですが、この問題では整数 i は 5 桁なので、回文数になる条件は、万の位(i/10000)=一の位(i%10)、かつ、千の位((i/1000)%10=十の位((i/100)%10)となります。コードは以下のようになりました。

abc090b-1.cpp
#include <bits/stdc++.h>
using namespace std;

int main() {
  int a, b;
  cin >> a >> b;

  int answer = 0;
  for ( int i=a; i<=b; i++ ) {
    if ( i/10000==i%10 && (i/1000)%10==(i%100)/10 ) {
      answer += 1;
    }
  }
  cout << answer << endl;
}

回答2 (AC)

回答1のように整数 i の各位を数式で表すのにピンと来ない場合には、文字列で処理することも可能です。整数 i を型変換した文字列 s が回文数になる条件は、s.at(0)==s.at(4) かつ s.at(1)==s.at(3) です。コードは以下のようになりました。

abc090b-2.cpp
#include <bits/stdc++.h>
using namespace std;

int main() {
  int a, b;
  cin >> a >> b;

  int answer = 0;
  for ( int i=a; i<=b; i++ ) {
    string s = to_string(i);
    if ( s.at(0)==s.at(4) && s.at(1)==s.at(3) ) {
      answer += 1;
    }
  }
  cout << answer << endl;
}

調べたこと

AtCoder の解説コンテスト全体の解説

回答1と同じ方針でした。

リンク

前後の記事

1
0
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
1
0