1
4

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 5 years have passed since last update.

数字の桁を求める

Posted at

Project Euler で酷使。
文字列にして処理してもいいのですが、せっかくなので。

こんなメソッドを用意する

int(long) の拡張メソッドにしてみます。
ただ基数で繰り返し割っていくだけです。

public static IEnumerable<int> Digits(this int n, int b = 10)
{
	if (n == 0)
		yield return 0;

	var q = n;
	while (q != 0)
	{
		yield return q % b;
		q /= b;
	}
}

bは基数です。既定値は10なので、10進数の場合の桁が得られます。
2にすれば2進数での桁になります。

こんな風に使う

var n = 23098432;
var result = n.Digits().ToArray();
// result => [2, 3, 4, 8, 9, 0, 3, 2]

※ シーケンスが1の位から順に返すことに注意してください。

元の数字に戻す

簡単に戻せます。

var digits = int[] { 2, 3, 4, 8, 9, 0, 3, 2 };
var n = digits.Select((x, i) => x * (int)Math.Pow(10, i)).Sum()
// n => 23098432
1
4
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
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?