LoginSignup
42
31

More than 1 year has passed since last update.

10進数の桁数を求める

Last updated at Posted at 2015-07-24

符号なし10進整数の桁数を求める関数 unsigned GetDigit(unsigned) を作る。
ただし、引数として0が与えられることはないものとする

10で割る

整数引数を、0になるまで10で割り続ける。割った回数が桁数。

unsigned GetDigit(unsigned num){
	unsigned digit = 0;
	while(num != 0){
		num /= 10;
		digit++;
	}
	return digit;
}

常用対数を使う

自然数 $a$ について、$\mathrm{floor}(\mathrm{log}_{10}({a})+1)$ は $a$ の10進桁数である。

unsigned GetDigit(unsigned num){
	return log10(num)+1;
}

文字列操作を利用して数える

人間の数え方に近い方法。

C

(/dev/nullみたいなものはCにないのかなあ...)

#define BUFSIZE 100
unsigned GetDigit(unsigned num){
	char buf[BUFSIZE];
	return sprintf(buf, "%u", num);
	//sprintfは出力に成功した場合、出力した文字数を返す
}

C++

unsigned GetDigit(unsigned num){
	return std::to_string(num).length();
}
42
31
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
42
31