0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

数値型1234を4321といった並び替えするにはどうすればよいか

Posted at

概要

書いてある通り。
何桁かの数字列があたえられたときに
並べ替えたりある桁とある桁を入れ替えるなどの操作をするときに数値型だと大変なので
一度ベクタに直しているがこれが大変に面倒
そこで何とかならんか試した

素朴に試した

戦略としては
数値型⇒string⇒vec⇒ここで並び替え⇒string⇒数値型
である。
https://qiita.com/kujirahand/items/fcb4f75dbdbfaf36aa75
https://qiita.com/smicle/items/29a4d5d1d14ad7f77f60
を参考にした

main.rs
fn main() {
let num:usize =1234;
  let stri: String = num.to_string();
  let mut cs: Vec<char> = stri.chars().collect();
  cs.sort_by(|a, b| b.cmp(a));
  let st: String = cs.iter().collect();
  let numm:  usize = st.parse().unwrap();
  println!("{}",numm)
}

素朴がすぎる

書いてある通り。
なんとかしたいなと。思いつくのは↓だがうーんという感じ

main2.rs
fn main() {
        let mut n = 1234;
        let mut a = vec![];
        while n > 0 {
            a.push(n % 10);
            n /= 10;
        }
        a.sort();
        let mut y = 0;
        for a in a.iter().rev() {
            y = 10 * y + *a;
        }
    println!("{}", y);
}

短くしたいが。。。

短くしただけになってしまった

main.rs
fn main() {
    let mut n = 1234;
    let mut cs:Vec<char> = n.to_string().chars().collect();
    cs.sort_by(|a, b| b.cmp(a));
  let numm:  usize = cs.iter().collect::<String>().parse().unwrap();
    println!("{:?}", numm);
}
0
1
2

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?