Java程序:计算给定整数的位数
假设给定一个整数作为输入,我们的任务是编写一个Java程序来计算该整数的位数。对于这个问题,创建一个计数器变量并将其初始化为0。将给定的整数值除以10,直到整数变为0,并为每次循环递增计数器变量。
使用while循环
Java中的while循环是一种控制流语句,允许根据给定的布尔条件重复执行代码。对于给定的问题,我们使用此循环来检查指定的整数值是否为0。如果值不为零,我们将给定的整数值除以10并递增计数变量。
当整数变为零时,循环将停止,计数器变量将保存总位数。
示例
下面的Java程序演示了如何使用while循环计算给定整数的位数。
public class CountingDigitsInInteger {
public static void main(String args[]) {
// to store the number of digits
int count = 0;
// given integer
int num = 1254566;
System.out.println("given number:: " + num);
// loop to count number of digits
while(num != 0){
num = num / 10;
count++;
}
System.out.println("Number of digits in the given integer are:: " + count);
}
}
以上代码的输出如下:
given number:: 1254566 Number of digits in the given integer are:: 7
使用String.valueOf()方法
Java.lang包的String类中提供了valueOf()方法。它用于返回传递参数的字符串表示形式。参数可以是任何数据类型,例如整数、字符或双精度浮点数。
在这种方法中,我们使用String.valueOf()方法将整数转换为其对应的字符串表示形式,然后找到其长度,这将给出位数。
示例
让我们看看String.valueOf()方法在计算位数中的实际应用。
public class CountingDigitsInInteger {
public static void main(String args[]) {
// given integer
int num = 254668899;
System.out.println("given number:: " + num);
int count = String.valueOf(num).length();
System.out.println("Number of digits in the given integer are:: " + count);
}
}
以上代码的输出如下:
given number:: 254668899 Number of digits in the given integer are:: 9
使用递归
这是计算给定整数位数的最佳解决方案。在递归方法中,我们创建一个方法,该方法将自身调用,直到给定的整型变量不等于零。在每次调用期间,它将划分整数并递增计数。
示例
在这个Java程序中,我们使用递归的概念来计算给定整数的位数。
public class CountingDigitsInInteger {
public static int counting(int num) {
if (num == 0) {
return 0;
}
return 1 + counting(num / 10);
}
public static void main(String[] args) {
// given integer
int num = 25468877;
System.out.println("given number:: " + num);
int count = counting(num);
System.out.println("Number of digits in the given integer are:: " + count);
}
}
以上代码的输出如下:
given number:: 25468877 Number of digits in the given integer are:: 8
广告
数据结构
网络
关系数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP