Why not login to Qiita and try out its useful features?

We'll deliver articles that match you.

You can read useful information later.

0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

正の整数の桁数を求める方法

Posted at

はじめに

正の整数の桁数を求める代表的なアルゴリズムをいくつか紹介します。

1. 常用対数を利用する

もっともスマートなのは、常用対数を利用する方法です。

def digit_count(n: int) -> int:
    import math
    return math.floor(math.log10(n)) + 1

2. ループを利用する

常用対数を求めるAPIがない場合は、整数を10で割っていき、何回割れるかを数えます。計算量はO(桁数)となり、十分に高速です。

def digit_count(n: int) -> int:
    if n == 0:
        return 1

    count = 0
    while n > 0:
        n //= 10
        count += 1
    return count

3. 文字列変換を利用する

この方法はナイーブでわかりやすく、桁数が小さい場合には問題なく動作します。ただし、桁数が大きくなると、次のような理由から想定通りに動作しないことがあります。

  • 数値から文字列への変換にオーバーヘッドがあり、処理に時間がかかる
  • メモリを大量に消費し、場合によってはメモリ不足(Out of Memory)が発生する可能性がある
def digit_count(n: int) -> int:
    return len(str(n))
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
neko_the_shadow

@neko_the_shadow

IT業界の片隅でひっそり生きるシステムエンジニアです(´・ω・`)

Comments

No comments

Let's comment your feelings that are more than good

0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Login to continue?

Login or Sign up with social account

Login or Sign up with your email address