10
11

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

ビット演算でフラグを立ててた時に、ふと数値の桁数を調べたくなった。
log関数を使うと求められるらしい。
はじめてlog関数使ったぁ。。

基数のデフォ値が2になってますが、
10のほうが使う機会多いかな?

実装

coffee
getDigits = (num, base = 2)->
  Math.log(num) / Math.log(base) + 1 | 0
js
var getDigits;

getDigits = function(num, base) {
  if (base == null) base = 2;
  return Math.log(num) / Math.log(base) + 1 | 0;
};

使い方

coffee
getDigits 10
# 4 (10 == 2進数で 1010)

getDigits 10, 10
# 2
js
getDigits(10);
// 4 (10 == 2進数で 1010)

getDigits(10, 10);
// 2
10
11
5

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
10
11

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?