How to extract the hundredths digit of an int [duplicate] - java

This question already has answers here:
Get a specific digit of a number from an int in Java [duplicate]
(4 answers)
Closed 3 years ago.
How to extract the hundred of an int variable?
For example, I have a random number:
int i = 5654217;
I want code to extract the number "2".
I tried to do
i/100
Which gave me 56542.
But I can't find a way to extract only the last number.
Too, I'm really unsure this is the best way to extract the hundred of the variable.

I am not 100% sure what you are asking so I will put the two guesses that I have of what your question is. If it doesn't answer your question please feel free to let me know, I will help you.
1) You are dividing an integer (int) by 100 and the last 2 digits disappear.
double x = (double)i/100.0;
//ints cannot store a decimal
2) You have a decimal (double) and are trying to output hundreds digit.
public int hundredthsDigit(double x){
if(x>0.0) return (x/100)%10;
//This moves the 100s digit to the 1s digit and removes the other digits by taking mod 10
return 10-Math.abs(x/100)%10;
// does practically the same thing, but is a work around as mod doesn't work with negatives in java
}

The modulus operator, % effectively gives you the remainder of a division.
You can get the last digit by getting the number, mod 10. Try (i / 100) % 10
You can read up more on modular arithmetic and such here: https://en.m.wikipedia.org/wiki/Modular_arithmetic

Please find code below:
package com.shree.test;
public class FindNumber {
public static int findNumberAt(int location,int inputNumber) {
int number = 0;
//number = (inputNumber % (location*10))/location; // This also works
number = (inputNumber/location)%10; // But as mentioned in other comments and answers, this line is perfect solution
return number;
}
public static void main(String[] args) {
System.out.println(findNumberAt(100, 5654217));
}
}

Related

How can I add a placeholder to a random Int then pull a single digit from that Int in Java?

I am new to Java and programming all together.. I am trying to make a program that ciphers a number for the user. The user inputs 5 digits separately so I add them together to get a total. I need to pull the first digit and second digit of the total and enter it into (firstDigit+key)%10 and (secondDigit+key)%10. Then need to combine the answer to each equation together.
My total needs to be two digits, so even if the user enters all 1's which would total to be 5, I need it to be displayed and seen as 05 so that both equations have a digit to use. It needs to be two digits. I cant seem to figure how to enter a place holder. I was thinking about trying to use:
if (total < 10)
but then what?
Secondly, the method I used below seems like a terrible way to pull a single digit from a number. I think I changed the int total into a string so I can use .substring to pull the digits, then converted back to an int. Surprisingly it works. Is there a better way to do this knowing that the number is random?
String totalString = Integer.toString(total);
String stringDigit1 = totalString.substring(0,1);
String stringDigit2 = totalString.substring(1,2);
int firstDigitInt1 = Integer.parseInt(stringDigit1);
int firstDigitInt2 = Integer.parseInt(stringDigit2);
int encodedDigit1 = (firstDigitInt1+key)%10;
int encodedDigit2 = (firstDigitInt2+key)%10;
System.out.println("Your encoded Number is: " + encodedDigit1 + encodedDigit2);
Your method for obtaining the individual digits is good, and if you want to maintain it I believe your intuition is correct, it should suffice to say:
if (total < 10) {
firstDigitInt1 = 0
}
This will work out with your following math.
Your method with substrings is far from terrible, but in case you wanted something more sleek you can instead say:
int Digit1 = total / 10;
int Digit2 = total % 10;
Here, you can take advantage of integer truncation (where an integer won't remember decimal places) to get the first digit, which also solves the first problem: 5 / 10 = 0 (in terms of ints). For the second digit, it suffices to say modulo 10, as it is the remainder once the total is divided by 10.

Issues Converting to Binary While Using a While Loop

I'm currently trying to solve the binary gap problem in java and started off with first trying to convert the decimal into binary using a while loop. I was testing it with different decimal inputs, but noticed after stepping through it, that on the final loop I'm getting integer overflow instead of appending a 1, (or at least I think I am, it goes from 100010000 to 411065418, I'm assuming because it multiples the 100010000 *10)
I tried stepping through it and This is my code currently:
public class BinaryGap {
public static void main(String[] args) {
// write your code in Java SE 8
int decimal = 529;
int ans =0;
//returns the number in binary but in big endian form
while(decimal != 0){
ans += (decimal % 2);
ans *= 10;
decimal /=2;
}
}
}
Any help in telling me where my line of thinking is wrong would be greatly appreciated
Your code is conceptually working fine - but variable 'ans' meets the limit of int - 2147483647. When +1 is added to this value - variable overflows and goes to minimal value.
To overcome it you can use type 'String' for 'ans' variable with small adjustments to code:
int decimal = 529;
String ans = "";
//returns the number in binary but in big endian form
while(decimal != 0){
ans += (decimal % 2);
decimal /=2;
}

Get a double with only two digits after the dot [duplicate]

This question already has answers here:
Java: How to set Precision for double value? [duplicate]
(11 answers)
Closed 5 years ago.
I’m working on a project at the java and can’t get a very important method to work
I have tried multiple solutions many from similar questions in stackoverflow none of the answers seems to work for may case
What I need is a simple method that will get a double and no matter what is the value of the double as long as there is more than two digits after the dot it will return the same number with only the first two digits after the dot
For example even if the input is “-3456.679985432333”
The output would be “-3456.67” and not “-3456.68” like other solutions gave me
The closest solution that seems to work was
public static double round (double d) {
d = (double) (Math.floor(d * 100)) / (100);
return d;
}
Yet it did failed when the input was “-0.3355555555555551” the output was “-0.34” and not “-0.33” as expected
I have no idea why did it fail and I’m out of solutions with only a few hours left for this project.
Edit: the fix I found was simple and worked great
public static double round (double d){
if (d>0) return (double) (Math.floor(d*100))/100;
else
{
return (double) (Math.ceil(d*100))/100;
}
}
Anyway thanks for everyone that explained to me what was wrong with my method and I will make sure to try all of your solutions
Explanation
Java is working correct. It's rather that floor returns the first integer that is less than (or equal) to the given value. It does not round towards zero.
For your input -0.335... you first multiply by 100 and receive -33.5.... If you now use floor you correctly receive -34 since its a negative number and -34 is the first integer below 33.5....
Solution
If you want to strip (remove) everything after the decimal you need to use ceil for negative numbers. Or use a method which always rounds towards zero, i.e. the int cast:
public static double round (double d) {
d = (double) ((int) (d * 100)) / (100);
return d;
}
(also see round towards zero in java)
Better alternatives
However there are dedicated, better, methods to achieve what you want. Consider using DecimalFormat (documentation):
DecimalFormat formatter = new DecimalFormat("##.##"); //
formatter.setRoundingMode(RoundingMode.DOWN); // Towards zero
String result = formatter.format(input);
Or any other variant, just search for it, there are plenty of questions like this: How to round a number to n decimal places in Java
Something like this would suffice:
public static double truncate(double input) {
DecimalFormat decimalFormat = new DecimalFormat("##.##");
decimalFormat.setRoundingMode(RoundingMode.DOWN);
String formatResult = decimalFormat.format(input);
return Double.parseDouble(formatResult);
}
returns:
-3456.67
and
-0.33
respectively for both examples provided.
you are able to do this, all you need to do is:
number * 10 or (100),
then convert to a int,
then back to double and / 10 (or 100).
10 = for 1 number after digit,
100 = for 2 (if i remember correctly).
public static double CustomRound(double number, int digits)
{
if (digits < 0)
throw new IllegalArgumentException();
long f = (long)Math.pow(10, digits);
number = number * f;
long rnd = Math.round(number);
return (double)(rnd / f);
}
An alternative approach:
public static double round(double number, int digits)
{
if (digits < 0)
throw new IllegalArgumentException();
BigDecimal bd = new BigDecimal(value);
bd = bd.setScale(digits, RoundingMode.HALF_UP);
return bd.doubleValue();
}

I am getting an exception Exception in thread "main" java.lang.ArithmeticException: / by zero [duplicate]

This question already has answers here:
ArithmeticException Java?
(8 answers)
Closed 5 years ago.
import java.util.Scanner;
public class MathsHacker {
public static int fact(int n)
{
if(n==0)
return 1;
else
return n*fact(n-1);
}
/*
I checked for 1 test case giving an input=5277
it results in exception :
Exception in thread "main" java.lang.ArithmeticException: / by zero
*/
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
int T =in.nextInt();
for(int a0 = 0; a0 < T; a0++)
{
int N = in.nextInt();
if(N==1)
{
System.out.println("0");
}
else
{
int res=fact(N)/(fact(N-2)*fact(2));
System.out.println(res);
}
}
}
5277! is a 17354 digit number.
Rather than calculating fact(N) / (fact(N-2) * fact(2)), you should realize that fact(N) / fact(N-2) is the same as N * (N-1), so if you calculate that instead, your calculation won't overflow.
Alternatively, change fact() to calculate using BigInteger, but you're really wasting time by multiplying 5277 numbers, then multiplying 5275 numbers, and dividing them, just to get a result that can be calculated by multiplying 2 numbers.
The maximum number an int can hold is up to:
2 ^ 31 - 1 = 2,147,483,647
However:
12! = 479,001,600
13! = 6,227,020,800
Then, this means that after 12! you cannot hold the value in an int.
While error given by the compiler is not really explicit, it's an overflow
You could use long but that's still:
2 ^ 63 - 1 = 9.223372036854776e18 ~ 9,223,372,036,854,776,000
21! = 5.109094217170944e19 ~ 51,090,942,171,709,440,000
As you can see it still overflows...
So, a better advice would be to use BigInteger class
Your calculations are massively overflowing the integer range (that's what the other answers already said). The overflow in itself happens silently, just giving wrong results (clipping all binary digits in front of the trailing 32 bits).
What leads to the java.lang.ArithmeticException: / by zero is that the binary representation of your (fact(N-2)*fact(2)) with N=5277 has more than 32 trailing zeros (in fact, it must be around 4000 trailing zeroes). And clipped to the trailing 32 bits, that's zero. That's where the division by zero happens.

Interesting thing happening when I take a number, multiply it by 10, and then add 1 [duplicate]

This question already has answers here:
Multiplication of two ints overflowing to result in a negative number
(5 answers)
Closed 9 years ago.
static int fn = 0;
static int sn = 0;
static boolean running = false;
public static void run()
{
while (running == true)
{
fn = numbers[0];
sn = numbers[1];
if (sign == 0)
{
input.setText(String.valueOf(fn));
}
}
}
static class one implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
if (Display.sign == 0)
{
Display.numbers[0] = Display.numbers[0] *10;
Display.numbers[0] = Display.numbers[0] +1;
}
}
}
This is the code for a calculator that I am programming (not all of it of course). This is the part where I display the number on the screen which I have done, but weirdly this works up until 10 characters
So after I get the program to display 1111111111 I want to do it once more and it gives me this weird number -1773790777. I am confused about how the program comes up with this. As you can see, above Display.numbers[] is the array I am storing the two numbers in. So to go over a place I multiply the number in the array by 10 then add 1. So how does this give me a negative number in the first place and what can I do to solve this problem?
Is your number overflowing?
You can check it by looking at Integer.MAX_VALUE (assuming you are using an integer). If you go over that you will loop will get weird results like this. See - http://javapapers.com/core-java/java-overflow-and-underflow/ for more details.
It's overflowing!
1111111111*10 + 1 = 11111111111 which is 0x2964619C7 in hexadecimal. It's a 34-bit value which can't be stored in a 32-bit int
In Java arithmetic operations wrap around by default, so if the result overflowed then it'll be wrapped back to the other end of the value range. See How does Java handle integer underflows and overflows and how would you check for it?
However due to the use of 2's complement, the result will be the lower bits of the result 11111111111 mod 232 = 2521176519 = 0x964619C7 which is -1'773'790'777 in 32-bit int, that's why you see the number. You should read more on binary, that's the basic of nowadays computers
In Java 8 you'll have an easier way to detect overflow with the new *Exact methods
The platform uses signed two's complement integer arithmetic with int and long primitive types. The developer should choose the primitive type to ensure that arithmetic operations consistently produce correct results, which in some cases means the operations will not overflow the range of values of the computation. The best practice is to choose the primitive type and algorithm to avoid overflow. In cases where the size is int or long and overflow errors need to be detected, the methods addExact, subtractExact, multiplyExact, and toIntExact throw an ArithmeticException when the results overflow. For other arithmetic operations such as divide, absolute value, increment, decrement, and negation overflow occurs only with a specific minimum or maximum value and should be checked against the minimum or maximum as appropriate.
https://docs.oracle.com/javase/8/docs/api/java/lang/Math.html

Categories

Resources