Java 程序计算整数的位数

javaobject oriented programmingprogramming更新于 2024/4/13 22:36:17

在本文中,我们将了解如何计算整数的位数。使用循环和计数器来计算整数的位数。

下面是相同的演示 −

输入

假设我们的输入是 −

数字:15161718

输出

所需的输出将是 −

结果为:8

算法

步骤 1 - 开始
步骤 2 - 声明两个整数值,即 my_count 和 my_input。
步骤 3 - 从用户那里读取所需值/定义值
步骤 4 - 使用 for 循环,将输入值除以 10,直到数字减少到其
最低可能值。每次增加计数器值。
步骤 5 - 显示计数器值作为结果
步骤 6 - 停止

示例 1

import java.util.Scanner;
public class Main {
   public static void main(String[] args) {
      int my_count , my_input;
      my_count = 0;
      System.out.println("Required packages have been imported");
      Scanner my_scanner = new Scanner(System.in);
      System.out.println("A reader object has been defined ");
      System.out.print("Enter the number : ");
      my_input = my_scanner.nextInt();
      for (; my_input != 0; my_input /= 10, ++my_count) {
      }
      System.out.println("The number of digits in the given input is: " + my_count);
   }
}

输出

Required packages have been imported
A reader object has been defined
Enter the number : 15161718
The number of digits in the given input is : 8

示例 2

这里,整数已经被预先定义,并且它的值被访问并显示在控制台上。

public class Main {
   public static void main(String[] args) {
      int my_count = 0, my_input;
      my_count = 0;
      my_input = 15161718;
      System.out.println("The number is defined as " +my_input);
      for (; my_input != 0; my_input /= 10, ++my_count) {
      }
      System.out.println("The number of digits in the given input is: " + my_count);
   }
}

输出

The number is defined as 15161718
The number of digits in the given input is: 8

相关文章


有用资源