爪哇程序查找数字的第一位和最后一位
在本文中,我们将查找Java中数字的第一位和最后一位。
要查找任何数字的第一位和最后一位,我们可以使用以下几种方法 模数 操作员或 战俘() and log()
methods of 数学
类 etc.
让’s see some examples.
在转到示例之前,让’首先创建一个算法来查找数字的第一位和最后一位。
算法
Step 1:
从用户处获取一个号码。
Step 2:
Create two variables firstDigit
and lastDigit
and initialize them by 0.
Step 3:
利用 模运算符(%
) to find last digit.
Step 4:
使用任一 而循环 and division operator (/
) or log()
and 战俘()
methods of 数学
类 to find
.
Step 5:
显示结果。
使用while循环
使用模运算符很容易返回数字的最后一位,我们可以使用while循环和除法运算符来获得数字的第一位。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
上市 类 主要 { 上市 静态的 虚空 主要(串 args[]) { 整型 数 = 502356997; 整型 firstDigit = 0; 整型 lastDigit = 0; lastDigit = 数%10; 系统.出.打印(“最后一位:”+lastDigit); 而(数!=0) { firstDigit = 数%10; 数 / = 10; } 系统.出.打印(“第一位数:”+firstDigit); } } |
输出量
第一位数:5
使用log()和pow()方法
If we want to use built-in methods
like log() and 战俘() of 数学 类, then we can use log()
method to get the 数 of 数字 and 战俘()
method to get divisor value that later on used to get the first digit of 数. See the example below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
上市 类 主要 { 上市 静态的 虚空 主要(串 args[]) { 整型 数 = 502356997; 整型 firstDigit = 0; 整型 lastDigit = 0; //查找最后一位 lastDigit = 数%10; 系统.出.打印(“最后一位:”+lastDigit); 整型 数字 = (整型)(数学.log10(数)); //查找第一个数字 firstDigit = (整型)(数 / (整型)(数学.战俘(10, 数字))); 系统.出.打印(“第一位数:”+firstDigit); } } |
输出量
第一位数:5
使用while循环和pow()方法
如果我们不这样做’t want to use log()
method then use 而循环 计算数字位数,并将其用于pow()方法以获取除数。请参见下面的示例。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
上市 类 主要 { 上市 静态的 虚空 主要(串 args[]) { 整型 数 = 502356997; 整型 firstDigit = 0; 整型 lastDigit = 0; 整型 计数 = 0; lastDigit = 数%10; 系统.出.打印(“最后一位:”+lastDigit); 整型 n = 数; 而(n!=0) { 计数++; n = n/10; } firstDigit = 数/(整型)数学.战俘(10, 计数-1); 系统.出.打印(“第一位数:”+firstDigit); } } |
输出:
第一位数:5
那’有关Java程序的全部内容,以查找java中数字的第一位和最后一位。