LoginSignup
0
0

More than 5 years have passed since last update.

[備忘録] int/long型での各桁の取得

Last updated at Posted at 2019-03-19

はじめに

C#でint型の各桁の値を取る時に、今まで$char$配列→$string$→$int$っていうくそだるい変換をしてたんですよね...
でもさすがにめんどくさすぎるなーって思ってて、スタックを使ったらいいかんじにできそうと思ったので書きました。

スタックを使っているのは知っている人には自明だと思いますが先入れ後出しなので。例えば、260だと、0→6→2の順番に入り、2→6→0の順番に出す。

コード

$int$型の場合

using System;
using System.Collections.Generic;

class Program
{
    static void Main(string[] args) {
        int s = int.Parse(Console.ReadLine());
        foreach(int i in digits(s)) {
            Console.WriteLine(i);
        }
    }
    static int[] digits(int n) {
        Stack<int> digit = new Stack<int>();
        while(n > 0) {
            digit.Push(n%10);
            n /= 10;
        }
        return digit.ToArray();
    }
}

$long$型の場合

using System;
using System.Collections.Generic;

class Program
{
    static void Main(string[] args) {
        long s = long.Parse(Console.ReadLine());
        foreach(int i in digits(s)) {
            Console.WriteLine(i);
        }
    }
    static long[] digits(long n) {
        Stack<long> digit = new Stack<long>();
        while(n > 0) {
            digit.Push(n%10);
            n /= 10;
        }
        return digit.ToArray();
    }
}
0
0
6

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