开发者

Retrieving the first digit of a number [duplicate]

开发者 https://www.devze.com 2023-01-01 22:31 出处:网络
This question already has answers here: Return first digit of an integer (25 answers) Closed 5 years ago.
This question already has answers here: Return first digit of an integer (25 answers) Closed 5 years ago.

I am just learning Java and am trying to get my pr开发者_运维知识库ogram to retrieve the first digit of a number - for example 543 should return 5, etc. I thought to convert to a string, but I am not sure how I can convert it back? Thanks for any help.

int number = 534;
String numberString = Integer.toString(number);
char firstLetterChar = numberString.charAt(0);
int firstDigit = ????


Almost certainly more efficient than using Strings:

int firstDigit(int x) {
    while (x > 9) {
        x /= 10;
    }
    return x;
}

(Works only for nonnegative integers.)


    int number = 534;
    int firstDigit = Integer.parseInt(Integer.toString(number).substring(0, 1));


firstDigit = number/((int)(pow(10,(int)log(number))));

This should get your first digit using math instead of strings.

In your example log(543) = 2.73 which casted to an int is 2. pow(10, 2) = 100 543/100 = 5.43 but since it's an int it gets truncated to 5


int firstDigit = Integer.parseInt(Character.toString(firstLetterChar));


int number = 534;
String numberString = "" + number;
char firstLetterchar = numberString.charAt(0);
int firstDigit = Integer.parseInt("" + firstLetterChar);


Integer.parseInt will take a string and return a int.


This example works for any double, not just positive integers and takes into account negative numbers or those less than one. For example, 0.000053 would return 5.

private static int getMostSignificantDigit(double value) {
    value = Math.abs(value);
    if (value == 0) return 0;
    while (value < 1) value *= 10;
    char firstChar = String.valueOf(value).charAt(0);
    return Integer.parseInt(firstChar + "");
}

To get the first digit, this sticks with String manipulation as it is far easier to read.


int number = 534;
int firstDigit = number/100; 

( / ) operator in java divide the numbers without considering the reminder so when we divide 534 by 100 , it gives us (5) .

but if you want to get the last number , you can use (%) operator

    int lastDigit = number%10; 

which gives us the reminder of the division , so 534%10 , will yield the number 4 .


This way might makes more sense if you don't want to use str methods

int first = 1;
for (int i = 10; i < number; i *= 10) {
    first = number / i;
}
0

精彩评论

暂无评论...
验证码 换一张
取 消