計算給定整數中數字個數的 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