0
0

yukicoder No.39 桁の数字を入れ替え 解説

Last updated at Posted at 2024-07-27

問題文

解説

入れ替えといわれるとswapを思い出すだろう。
ただswapは整数型の桁には使えないので、文字列でできないか考える。
ここで、答えとなる数字と元の数字の桁は変わらないということが言える。
つまり、辞書順比較による事故(10<100<11みたいな)が起こらない。
よって、事前にstring型としていい感じにswapをし、辞書順で遅かったらそれを答えの候補にするといいう感じでできる。

C++での解答例

#include <bits/stdc++.h>
using namespace std;

int main(){
  string n;cin>>n;
  string ans=n;
  for(int i=0;i<n.size();i++)
    for(int j=i+1;j<n.size();j++){
      string t=n;
      swap(t[i],t[j]);
      ans=max(ans,t);
    }
  cout<<ans<<endl;
}
0
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
0
0