Home  >  Article  >  Backend Development  >  C# program to calculate total number of digits in a number

C# program to calculate total number of digits in a number

王林
王林forward
2023-09-12 15:25:021124browse

C# 程序计算数字中的总位数

Let us assume that the number we have is 12. We declared and initialized a uint variable by assigning a decimal literal. The binary representation of

uint val = 12;

12 is −

1100

The number of digits above is 4, so to find the total number of digits, use the Math.log() method−

uint res = (uint)Math.Log(val , 2.0) + 1;

Example

You can try running the following code to calculate the total number of digits in a number.

Live Demo

using System;
public class Demo {
   public static void Main() {
      uint val = 12; // 1100 in binary
      uint res = (uint) Math.Log(val, 2.0) + 1;
      // 1100 has 4 bits
      Console.WriteLine("Total bits: " + res);
   }
}

Output

Total bits: 4

The above is the detailed content of C# program to calculate total number of digits in a number. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete