如何在Java中返回整数的第一个数字。?
即。
345
返回3的int。
答案 0 :(得分:40)
最简单的方式是使用String.valueOf(Math.abs((long)x)).charAt(0)
- 这将为您提供char
1 。要将其作为整数值,您可以减去“0”(如在Unicode中,“0”到“9”是连续的)。
当然,这有点浪费。另一种方法是取绝对值,然后循环除以10,直到数字在0-9范围内。如果这是作业,那就是我给出的答案。但是,我不会为它提供代码,因为我认为可能是作业。但是,如果您提供意见并编辑答案以解释您正在做的事情以及您遇到的问题,我们可能会提供帮助。
1 需要注意的一点是,Integer.MIN_VALUE
的绝对值无法表示为int
- 因此您可能应首先转换为{{ 1}},然后使用long
,然后进行算术运算。这就是为什么那里有演员。
答案 1 :(得分:19)
另一种方式:
public int firstDigit(int x) {
if (x == 0) return 0;
x = Math.abs(x);
return (int) Math.floor(x / Math.pow(10, Math.floor(Math.log10(x))));
}
答案 2 :(得分:18)
public static int firstDigit(int n) {
while (n < -9 || 9 < n) n /= 10;
return Math.abs(n);
}
也应该很好地处理负数。在这种情况下,将返回负数第一位。
答案 3 :(得分:7)
忽略负值会导致:
(""+345).charAt(0);
答案 4 :(得分:6)
缺少递归解决方案:
int getFirstInt(int input) {
if (input > 0 ? input < 10 : input > -10) {
return input > 0 ? input : -input;
}
return getFirstInt(input / 10);
}
我不会在现实生活中使用三元运算符但是 - 它不是很漂亮吗? ;)
答案 5 :(得分:3)
<强>更新强> 要处理Integer.MIN_VALUE并将Math.abs()和强制转换保持在循环之外:
public static int getFirstDigit(int i) {
i = Math.abs(i / (Math.abs((long)i) >= 10 ) ? 10 : 1);
while (i >= 10 )
i /= 10;
return i;
}
原始答案:
return Math.abs(i);
} public static int getFirstDigit(int i) {
while (Math.abs(i) >= 10 ) {
i = i / 10;
}
return Math.abs(i);
}
答案 6 :(得分:3)
我发现这个更简单:
int firstDigit(int num)
{
if(num/10 == 0)
return num;
return firstDigit(num/10);
}
答案 7 :(得分:2)
家庭作业提示:将其转换为字符串并返回第一个字符。
答案 8 :(得分:2)
最快的方式是:
答案 9 :(得分:1)
看看提供的代码,似乎有点过于复杂化整个事情,这是一个简单的解决方案......
int number = 4085;
int firstDigit = number;
while (firstDigit > 9)
{
firstDigit = firstDigit / 10;
}
System.out.println("The First Digit is " + firstDigit);
答案 10 :(得分:1)
假设数字是int类型
因此,
package com.qtby.gxwlc;
import org.apache.cordova.CordovaChromeClient;
import org.apache.cordova.CordovaInterface;
import org.apache.cordova.CordovaWebView;
import com.jsdemo.ClientTool;
import com.jsdemo.JsNativeFunc;
import android.content.Intent;
import android.webkit.JsPromptResult;
import android.webkit.WebView;
public class CustomerWebChromeClient extends CordovaChromeClient {
public CustomerWebChromeClient(CordovaInterface ctx, CordovaWebView app){
super(ctx, app);
}
JsNativeFunc jsNativeFunc;
public JsNativeFunc getJsNativeFunc(){
return jsNativeFunc;
}
public boolean isJsNativeFunc(int requestCode){
if(jsNativeFunc == null)
return false;
return jsNativeFunc.isJsNativeFunc(requestCode);
}
public void jsResult(int requestCode, int resultCode,
Intent intent){
jsNativeFunc.jsResult(requestCode, resultCode, intent);
}
@Override
public boolean onJsPrompt(WebView view, String origin, String message,
String defaultValue, JsPromptResult result) {
if(ClientTool.callNativeFunc(message)){
return super.onJsPrompt(view, origin, message, defaultValue, result);
}
return true;
}
return super.onJsPrompt(view, origin, message, defaultValue, result);
}
}
或另一种方法是将String更改为char并从char
获取数值e.g。
public void Start()
{
_timer.Elapsed += new ElapsedEventHandler(timer_Elapsed);
_timer.Interval = _context.adpSettings.SyncInterval * 1000;
_timer.AutoReset = false;
_timer.Enabled = true;
}
private void timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
var t = ExecuteTransactionReportAsync();
_timer.Start();
}
private async Task ExecuteTransactionReportAsync()
{
AccessEvent accessEvent = new AccessEvent();
.... do some logic
await _context.GetConnector().EnqeueuEventAsync(accessEvent);
}
答案 11 :(得分:1)
int a = 354;
int b = (int)(a / Math.Pow(10, (int)Math.Log10(a))); // 3
答案 12 :(得分:1)
int main(void) {
int num = 3421;
while (num*num + 10 - num*(1 + num) <= 0) {
num *= (num - 0.9*num)/num;
}
std::cout << num << std::endl;
}
答案 13 :(得分:0)
我认为这可能是一个很好的方法:
public static int length(int number) {
return (int)Math.log10(Math.abs(number)) + 1;
}
public static int digit(int number, int digit) {
for (int i = 0; i < digit; i++) {
number /= 10;
}
return Math.abs(number % 10);
}
适用于负数和正数。 digit(345, length(345) - 1)
将返回3
,digit(345, 0)
将返回5,例如等等...
答案 14 :(得分:-1)
这是Groovy,但转换为Java应该很容易:
int firstNum(int x) {
a = Math.abs(x)
sig = Math.floor(Math.log10(a))
return a / Math.pow(10, sig)
}
结果:
常规&GT;的println(firstNum(345))
3常规&GT;的println(firstNum(3452))
3常规&GT;的println(firstNum(-112))
1常规&GT;的println(firstNum(9999))
9常规&GT;的println(firstNum(Integer.MAX_VALUE的))
2常规&GT; println(firstNum(Integer.MIN_VALUE + 1))
2
答案 15 :(得分:-1)
这是分别获取整数的第一个和第二个数字的一种非常简单的方法,但这只适用于两位数字!
int firstDigit = number / 10;
int secondDigit = number % 10;
对于用户可能输入更多或更少数字的情况,但您可能不知道有多少数字,您可以尝试这种方法,但其他答案对此案例有更好的解决方案。我刚刚编写了这个完整的程序,您可以将其粘贴到编译器中并运行。一旦你看到模式,你可以检查任意数量的数字,然后只有一个长度大于你想要接受的捕获:
package testingdigits;
import java.util.Scanner;
public class TestingDigits {
Scanner keyboard = new Scanner(System.in);
public static void main(String[] args)
{
Scanner keyboard = new Scanner(System.in);
System.out.printf("\nEnter a number to test:");
int number = keyboard.nextInt();
int length = (int) Math.log10(number) + 1; //This gets the length of the number of digits used
//Initializing variables first to prevent error
int firstDigit = 0, secondDigit = 0, thirdDigit = 0, fourthDigit = 0, fifthDigit = 0, sixthDigit = 0;
if (length == 1)
{
firstDigit = number;
System.out.println("" + firstDigit);
}
if (length == 2)
{
firstDigit = number / 10; //For example, 89/10 will output 8.9 and show as 8 in this case.
secondDigit = number % 10;
System.out.println("" + firstDigit + "" + secondDigit);
}
if (length == 3)
{
firstDigit = number / 10 / 10; // 123/10/10 is 1.23 and will show as 1
secondDigit = number / 10 % 10;
thirdDigit = number % 10;
System.out.println("" + firstDigit + "" + secondDigit + "" + thirdDigit);
}
if (length == 4)
{
firstDigit = number / 10 / 10 / 10;
secondDigit = number / 10 / 10 % 10;
thirdDigit = number / 10 % 10;
fourthDigit = number % 10;
System.out.println("" + firstDigit + "" + secondDigit + "" + thirdDigit + "" + fourthDigit);
}
if (length == 5)
{
firstDigit = number / 10 / 10 / 10 / 10;
secondDigit = number / 10 / 10 / 10 % 10;
thirdDigit = number / 10 / 10 % 10;
fourthDigit = number / 10 % 10;
fifthDigit = number % 10;
System.out.println("" + firstDigit + "" + secondDigit + "" + thirdDigit + "" + fourthDigit + "" + fifthDigit);
}
//You can probably see the pattern by now. It's not an elegant solution, but is very readable by even beginners:
if ((length == 6))
{
firstDigit = number / 10 / 10 / 10 / 10 / 10; //The first digit is divided by 10 for however many digits are after it
secondDigit = number / 10 / 10 / 10 % 10;
thirdDigit = number / 10 / 10 / 10 % 10;
fourthDigit = number / 10 / 10 % 10;
fifthDigit = number / 10 % 10; //The second to last always looks like this
sixthDigit = number % 10; //The last digit always looks like this no matter how big you go
System.out.println("" + firstDigit + "" + secondDigit + "" + thirdDigit + "" + fourthDigit + "" + fifthDigit + "" + sixthDigit);
}
if ((length > 6))
{
//The main problem with this approach is that you have to define in advance how many digits you are working with
//So it's simple, but not very elegant, and requires something to catch unexpected input from the user.
System.out.println("Invalid Input!");
}
}
}
作为一个程序,它只输出您输入的数字,但正如您所看到的那样,它表明它能够分离用户输入的数字,因此您可以用它作为一个简单程序的测试,但同样,它不如这里的其他一些解决方案好,它只是一个适合初学者的可读方法。它也接受否定就好了。
另外:如果你以double开头,可以使用以下命令转换为int并截断小数:
numberInt = (int)number;
答案 16 :(得分:-1)
//Try this one.
Scanner input = new Scanner(System.in);
System.out.println("enter first 9 digits: ");
String x = input.nextLine();
String x1 = x.substring(0,1);
int d1 = Integer.parseInt(x1);
System.out.println(d1);
// the substring gives the position of extraction. method dont seem to work for letters though
答案 17 :(得分:-1)
int firstNumber(int x){
int firstN = x;
while(firstN > 9){
firstN = (firstN - (firstN%10))/10;
}
return firstN;
}
答案 18 :(得分:-1)
这是一个较小的版本来获取所有位置的数字,它使用负值(不是十进制)。
int number = -23456;
int length = (int) Math.log10(Math.abs(number)) + 1; //This gets the length of the number of digits used
//Math.abs to change negative int to positive
System.out.println("Digit at pos " + 1 + " is :- " + (int)(Math.abs(number)/Math.pow(10,(length-1))));
for (int i = 2; i <= length; i++){
System.out.println("Digit at pos " + i + " is :- " + (int)(Math.abs(number)/Math.pow(10,(length-i))%10));
}
答案 19 :(得分:-1)
public static void firstDigit(int number){
while(number != 0){
if (number < 10){
System.out.println("The first digit is " + number);
}
number = number/10;
}
}
当您调用它时,您可以使用Maths.abs使其适用于负数:
firstDigit(Math.abs(9584578));
这将返回9
答案 20 :(得分:-1)
我认为更简单:
int firstDigit = i-(i/10)*10 // i is an integer or long value, positive or negative.
答案 21 :(得分:-2)
这种方式对我很有用,但它确实涉及从int转换为string并返回int。
Integer.parseInt(String.valueOf(x).substring(0,1));