首页 > 代码库 > Java编程:用两种方法求输入正整数的位数。

Java编程:用两种方法求输入正整数的位数。

import java.util.Scanner;

public class Test {
	public static void main(String[] args) {
		
		Scanner sc = new Scanner(System.in);
		int n = sc.nextInt();
		//把整数n转换为字符串求其长度
		int len = Integer.toString(n).length();
		System.out.println("用字符串的方式求其长度len="+len);
		
		//用while循环求其长度
		int count = 0;
		while(true)
		{
			count++;
			n = n/10;
			if(n==0)
				break;
		}
		System.out.println("用while循环求其字符串的长度len"+count);
		
	}

}

Java编程:用两种方法求输入正整数的位数。