This question already has answers here:
Way to get number of digits in an int?
(29 answers)
Closed 9 years ago.
I have do detect the amount of digits on a number. For example, 329586 has 6 digits.
What I done, is simply parsing the number to string, and getting the string length, like:
number.toString().length()
But, is there a fastest way to count digits on a number? I have to use this method several times, so I think using toString() can impact performance.
Thanks.
Math.floor(Math.log10(number) + 1)
// or just (int) Math.log10(number) + 1
For example:
int number = 123456;
int length = (int) Math.log10(number) + 1;
System.out.println(length);
OUTPUT:
6
how about this homebrewed solution:
int noOfDigit = 1;
while((n=n/10) != 0) ++noOfDigit;
Try this :
Working Example
public class Main {
public static void main(String[] args) {
long num = -23;
int digits = 0;
if (num < 0)
num *= (-1);
if (num < 10 && num >= 0)
digits = 1;
else {
while(num > 0) {
num /= 10;
digits++;
}
}
System.out.println("Digits: " +digits);
}
}
Related
This question already has answers here:
Java reverse an int value without using array
(33 answers)
Closed 3 years ago.
I'm a Java beginner so please pardon me if the question seems silly but I already searched the forums but it seems like no one has my problem.
I need to reverse the digits of an integer, and my class hasn't covered while or if loops yet, so I can't use those. All answers I can find on stackoverflow use those, so I can't use those.
the input I am given is below 10000 and above 0 and the code I have written has no problem reversing the integer if the input is 4 digits (e.g. 1000 - 9999) but once the input is between 1 - 999 it creates zeroes on the right hand side but according to the answer sheets its wrong.
For example: 1534 gets turned into 4351, but
403 becomes 3040 instead of the 304 it should be, and 4 becomes 4000 instead of 4.
I've tried different things in the code but it seems to just keep giving the same answer. Or maybe I'm just missing some key mathematics, I'm not sure.
Scanner scan = new Scanner(System.in);
System.out.println ("Enter an integer:");
int value = scan.nextInt();
int digit = (value % 10);
value = (value / 10);
int digit2 = (value % 10);
value = (value / 10);
int digit3 = (value % 10);
value = (value / 10);
int digit4 = (value % 10);
String reversednum = ("" + digit + digit2 + digit3 + digit4);
System.out.println ( reversednum);
and
Scanner scan = new Scanner(System.in);
System.out.println ("Enter an integer:");
int value = scan.nextInt();
int digit = (value % 10);
int reversednum = (digit);
value = (value /10);
digit = (value % 10);
reversednum = (reversednum * 10 + digit);
value = (value / 10);
digit = (value % 10);
reversednum = (reversednum * 10 + digit);
value = (value / 10);
digit = (value);
reversednum = (reversednum * 10 + digit);
System.out.println (reversednum);
What am I doing wrong?
You can convert from int to String -> reverse String -> convert again in int.
This is a code example.
public int getReverseInt(int value) {
String revertedStr = new StringBuilder(value).reverse().toString();
return Integer.parseInt(revertedStr);
}
Your code assumes that the number can be divided by 1000, which is clearly not the case for numbers below 1000. So add some if statements:
public int reverseNumber(int n) {
// step one: we find the factors using integer maths
int s = n;
int thousands = s / 1000; // this will be 0 if the number is <1000
s = s - thousands*1000;
int hundreds = s / 100; // this will be 0 if the number is <100
s = s - hundreds*100;
int tens = s / 10; // etc.
s = s - tens*10;
int ones = s;
// then: let's start reversing. single digit?
if (n<10) return n;
// two digits?
if (n<100) {
return ones*10 + tens;
}
// etc.
if (n<1000) {
return ones*100 + tens*10 + hundreds;
}
if (n<10000) {
return ones*1000 + tens*100 + hundreds*10 + thousands;
}
// if we get here, we have no idea what to do with this number.
return n;
}
Without spoon-feeding you code (leaving the value of writing your own homework code intact)...
Although you've said you can't use a loop, I don't think there's a sane approach that doesn't use one. Your basic problem is you have hard-coded a solution that works when the number happens to have 4 digits, rather than using code that adapts to a variable length. ie, are not using a loop.
All is not lost with your code however. You have figured out the essence of the solution. You just need to convert it to work processing one digit at a time. Consider using recursion, that divides the number by 10 each time and continues until the number is zero. Of course, you’ll have to capture the end digit before it’s lost by division.
Pseudo code may look like:
pass in the number and the current result
if the number is 0 return result
multiply result by 10 and add remainder of number divided by 10
return the result of calling self with number divided by 10 and result
then call this passing number and zero
Using modulus and division:
int nbr = 123; // reverse to 321 or 3*10*10 + 2*10 + 1
int rev = 0;
while(nbr > 0) {
rev *= 10; // shift left 1 digit
int temp = nbr % 10; // get LO digit
rev += temp; // add in next digit
nbr /= 10; // move to next digit
}
Or a recursive method:
public static int reverseInt(int number, int value) {
switch(number) { // is this conditional statement allowed???
case 0:
return value;
}
value *= 10;
int lod = number % 10;
value += lod;
number /= 10;
return reverseInt(number, value);
}
I've been trying to sum a certain digit from a number, for example
Number: 5
Input: 54365
Output: The sum of 5's is 10
Second example:
Number: 5
Input: 5437555
Output: The sum of 5's is 20
I've managed to separate the digits yet I couldn't find the condition to sum
a certain number (for instance number 5 like the examples).
I'd appreciate to hear your idea of doing it
public static void main(String[] args) {
int sum = 0;
int number = MyConsole.readInt("Enter a number:");
while (number > 0) {
if (number % 10 == 8) {
sum += 8;
} else {
number /= 10;
}
}
System.out.println("The sum of 8's is:" + sum);
}
My way of separating the numbers.
Also i have a small program to get input instead of using scanner since we still haven't went through it in class.
Your requirement seems reasonably clear to me.
Given a number
final int number = 5;
And a starting number
final int input = 54365;
The easiest way is to convert that number to a String
final int inputStr = String.valueOf(input);
Then, you can filter each char for it, and sum them
final int sum =
inputStr.chars() // Get a Stream of ints, which represent the characters
.map(Character::getNumericValue) // Convert a char to its numeric representation
.filter(i -> i == number) // Filter for the designated number
.sum(); // Sum all the filtered integers
Output: 10
Using the same approach, but with an old-style for loop
final int input = 54365;
final int inputStr = String.valueOf(input);
final int number = 5;
int sum = 0;
for (final char c : inputStr.toCharArray()) {
final int n = Character.getNumericValue(c);
if (n == number) {
sum += number;
}
}
Your solution can work
int number = 5;
int input = 543655;
int sum = 0;
while (input > 0) {
if (input % 10 == number) {
sum += number;
}
input /= 10;
}
This question already has answers here:
The literal xyz of type int is out of range
(5 answers)
Closed 8 years ago.
The code is supposed to give back the biggest prime number.
More about the task here: https://projecteuler.net/problem=3
int checkFactors(double na) {
long n = (long) na;
int biggestPrimeFactor = 0;
for (int i = 1; i < n; i++)
if (n % i == 0 && isPrimFaktor(i) && i > biggestPrimeFactor)
biggestPrimeFactor = i;
return biggestPrimeFactor;
}
boolean isPrimeFactor(int n) {
int length= 0;
for (int i = n; i > 0; i--)
if (n % i == 0)
length++;
if (length== 2)
return true;
return false;
}
I decided to make the parameter of checkFactors() a double because I tried to test why my code didn't work properly.
System.out.println(checkFactors(13195));
works and returns "29".
However, System.out.println(checkFactors(600851475143));
does not work,
"600851475143 of type int is out of range".
System.out.println(checkFactors(600851475143.0));
does compile but gives me after a couple of seconds an ArithmeticException.
600851475143 of type int is out of range
This number is bigger than int can store. Appending .0 to the number converts the number into a double which can represent that number
Instead of .0 you can do checkFactors(600851475143d) which ensure the number is a double and not an int
Use long as a data type for na and also biggestPrimeFactor. The values are too large for storing in an int variable.
Try to make Your parameter back to long and make letter L after your large number like this 600851475143L, I think it will work
I am trying to find a way to reverse a number without
Converting it to a string to find the length
Reversing the string and parsing it back
Running a separate loop to compute the Length
i am currently doing it this way
public static int getReverse(int num){
int revnum =0;
for( int i = Integer.toString(num).length() - 1 ; num>0 ; i-- ){
revnum += num % 10 * Math.pow( 10 , i );
num /= 10;
}
return revnum;
}
But I would Like to implement the above 3 conditions.
I am looking for a way , possibly using the bit wise shift operators or some other kind of bitwise operation.
Is it possible ? If so how ?
PS : If 1234 is given as input it should return 4321. I will only be reversing Integers and Longs
How about:
int revnum = 0;
while (num != 0) {
revnum = revnum * 10 + (num % 10);
num /= 10;
}
return revnum;
The code expects a non-negative input.
This may or may not matter to you, but it's worth noting that getReverse(getReverse(x)) does not necessarily equal x as it won't preserve trailing zeroes.
How about this? It handles negative numbers as well.
public int getReverse(int num){
int rst=0;
int sign;
sign=num>0?1:-1;
num*=sign;
while(num>0){
int lastNum = num%10;
rst=rst*10+lastNum
num=num/10;
}
return rst*sign;
}
Integer.MAX_VALUE or Integer.MIN_VALUE is not at all considered in any of the solutions.
For eg: if the input is -2147483647 or 2147483647 the o/p will be 1126087180 and -1126087180 respectively.
Please try the below solutions where both the conditions are handled, so if at any point of time the number is going beyond the boundary conditions i.e., INPUT_VALUE > Integer.MAX_VALUE or INPUT_VALUE < Integer.MIN_VALUE it would return 0
class ReversingIntegerNumber {
public int reverse(int originalNum) {
boolean originalIsNegative = originalNum > 0 ? false : true;
int reverseNum = 0;
int modValue;
originalNum = Math.abs(originalNum);
while(originalNum != 0) {
modValue = originalNum % 10;
if(reverseNum > (Integer.MAX_VALUE - modValue)/10) {
return 0;
}
reverseNum = (reverseNum * 10) + modValue;
originalNum /= 10;
}
return originalIsNegative ? -1 * reverseNum : reverseNum;
}
}
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 program 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;
}