This is the actual question:
Write an interactive program that adds two integers of up to 50 digits each
(Represents integer as an array of digits).
This is a homework question and the language to be used is Java. I got this far but I don't think it is even close.
1. It is not taking input more than 20 digits but have to work with 50 digits.
2. The method 'integerToDigits' is producing two arrays but i am unable to sort out how to use them and add them in the main method.
Help please.
package One;
import java.util.Scanner;
public class AddInt {
public static void main(String[] args) {
Long x,y;
Long a[] = new Long[50];
Long b[] = new Long[50];
System.out.println("Please enter two numbers which have no more than 50 digits: ");
Scanner s = new Scanner(System.in);
x = s.nextLong();
y = s.nextLong();
System.out.println(x+ "and "+y);
integerToDigits(x);
integerToDigits(y);
}
public static Long[] integerToDigits(Long n){
Long digits[] = new Long[50];
Long temp = n;
for(int i = 0; i < 50; i++){
digits[49-i] = temp % 10;
temp /= 10;
}
return digits;
}
}
It is not taking input more than 20 digits but have to work with 50 digits.
This is because you're using x = s.nextLong() which is trying to convert the input to a long. The maximum long value is 9223372036854775807 which is nowhere near 50 digits. You'll need to get the input as a String and then covert that to your int[]
The method 'integerToDigits' is producing two arrays, but I am unable to sort out how to use them and add them in the main method.
In terms of adding up the arrays of digits, you can use the same process we learn very early on in school.
Add the units, then carry over any tens.
Add the tens and carry over any hundreds.
Add the hundreds and carry over any thousands.
...
This process can be iterated adding each order of magnitude with the carry over from the previous one.
Hopefully those tips give you a way to solve your problem.
If you do want a solution, I've produced one here that seems to work as you require. (Although not in ideone apparently)
If "Represents integer as an array of digits" is a suggestion and not a requirement a solution using BigInteger would look something like:
// read numbers from input
// store first value as String "firstNumber"
// store second value as String "secondNumber"
BigInteger a = new BigInteger(firstNumber);
BigInteger b = new BigInteger(secondNumber);
BigInteger result = a.add(b);
System.out.println("Result is " + result.toString());
If "Represents integer as an array of digits" is a requirement, well, then it's a silly assignment :) No one would store an integer like that. Worst case, I'd store it as a String if BigInteger was not allowed.
Related
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.
here i have a problem. i want a user to input some numbers, then i will convert the input into a string,i will then count the length of the string, and if it is less than 8,i want to add more zeros to the input to make it 8 so that i can do some staff with the number. i have tried to use decimalformat but its not working. plz help.
thanks in advance
int s=Integer.parseInt(s1.readLine());
String news=String.valueOf(s);
if(news.length()<8){
DecimalFormat myformat=new DecimalFormat("00000000");
String out= myformat.format(s);
int onth=(Integer.valueOf(out)).intValue();
s=onth;
}else{
System.out.format("your number is: %d\n",s);
Forget about using the DecimalFormat.
Change your format to the following
System.out.format("your number is: %08d\n",s)
The %08d will lead with zeros, to a width of 8.
This will only display the number in the format you've requested. As stated elsewhere in this thread, treating it as a number would remove the leading zeros.
If you want to store it in a String variable however, you can use
String intString = String.format("%08d", s);
to store it.
Update *
As you have a specific need to get a series of numbers between a substring
the following code will do what you want.
private static int getSubNumber(int startIndex, int stopIndex, int number) {
String num = String.format("%08d", number);
return Integer.parseInt(num.substring(startIndex, stopIndex));
}
If you pass in the number you want to convert, it will change it to a string, and then convert the substring between the two indexes you pass in back into a number
System.out.println(getSubNumber(2,5,12345678)); // = 345
System.out.println(getSubNumber(2,5,12345)); // = 12
System.out.println(getSubNumber(2,5,123)); // = 0
This is non inclusive, getSubNumber(2,5,...) gets values at position 2,3 and 4 NOT 5.
For your example of 144, use start index 2, stop index 6 for positions 2, 3, 4 and 5
System.out.println(getSubNumber(2,6,144)); // = 1
DecimalFormat is to format numbers in the way we give the pattern.
And to append zeros, please follow this:
Add leading zeroes to a string
If you need to add 0 after the value, you can multiply it by 10 pow the number of missing 0:
int result = Integer.parseInt(news);
if(news.length()<8){
int diff = 8 - news.length();
result = result * Math.pow(10, diff); // ==> result = result * 10^(8 - news.length())
}
I think that's the simpliest way to do that.
Edit Ahhh, yes... There is prefix in the question. Nevermind!
Even if you prefix an int with zeros the actual value will change to the original value. If you want padding you'll have to go with string. The out variable will give you the result.
Update based on comment
import java.util.Scanner;
public class SquareSubString {
public static void main(String[] args) {
String userInputSquare = getSquaredInput();
int digits2to5 = Integer.parseInt(userInputSquare.substring(2, 6));
System.out.println("Squre of digits 2 to 5 is : " + (digits2to5 * digits2to5));
}
private static String getSquaredInput() {
System.out.println("Enter a number : ");
Scanner in = new Scanner(System.in);
int input = in.nextInt();
in.close();
return String.format("%08d", (input * input));
}
}
Okay, I have a problem with taking numbers and storing them into an int array. I have the basic outline of the code, but I'm having trouble storing them in a way that displays when there is a 0 in front of a group of non-zero numbers.
For example, when I do this:
String s = "030142165109876";
private static void breakCode(String s){
int x = s.length(), m = 0, l = x/5;
String[] array = s.split("");
int[] output = new int[l+1];
int[] results = new int[array.length];
for(int i = 0; i < x/5; i++){
double y = 0;
if(i == 0){
for(int r = 5; r >= 0; r--){
try {results[m] = Integer.parseInt(array[m]);} catch (NumberFormatException nfe) {};
y = y + (Math.pow(10, r) * results[m]);
m++;
}
output[i] = (int) y;
System.out.println(output[i]);
}
if (i != 0){
for(int r = 4; r >= 0; r--){
try {results[m] = Integer.parseInt(array[m]);} catch (NumberFormatException nfe) {};
y = y + (Math.pow(10, r) * results[m]);
m++;
}
output[i] = (int) y;
System.out.println(output[i]);
}
}
}
The output for this code is:
3014
21651
9876
How do I get the zero to be held in place on the left hand side? I know it's because I'm using power functions and the leftmost value to that power wont show up when printing. Is there any way to force the int array to hold 5 digits so that when the number is less than 10000 it will hold the left most value as 0? The second line doesn't start with a 0 so it holds all 5 digits properly, but not the first and third (I wrote the numbers as an example, the real program uses randomized digits).
Full disclosure, this is for an assignment, but the programmatic methods I've thought up to solve this issue don't solve it. I have searched for my specific problem extensively throughout this website (trust me, I've grown to love searching through here), but I haven't picked up any useful tidbits regarding this specific problem. This is also my own way of solving the problem, and if there's a way of holding 5 digits for a place in an int array then I'd love to do it with my solution rather than having my friend's coding buddy come up with a really elegant solution that isn't my own brainchild.
Thank you
P.S. I'm very verbose
First split the input into strings 5 chars long, then parse them into ints:
String[] parts = str.split("(?<=\\G.{5})");
int[] nums = new int[parts.length];
for (int i = 0; i < parts.length; i++)
nums[i] = Integer.parseInt(parts[i]);
The regex for split() causes a split after every 5 chars - the \G (end of last match) ensures no overlap.
It's unclear what your exact problem is, but if it's just outputting the numbers with leading zeroes intact, I would just output parts and not bother with parsing them into an int[]. IF it's about outputting int values with leading zeroes, use
System.out.println(new DecimalFormat("00000").format(nums[i]));
Zeros in format patterns mean always print a digit there.
Numbers are always stored[1] and printed without zeroes by default. It is how Java (and almost all other languages) work.
If you just want to print 5 digits, consider printf.
printf("%05d\n", output[i]);
If you really want to always store 5 digits, use String[] and split using String methods. The substring method of String should do what you want easily.
[1] Conceptually (and in most, if not all, practical purposes) we treat numbers are stored without leading zeroes. In fact, strictly speaking, it does not. Java allocates some memory to store your numbers, and set this piece of memory with zeroes. As a whole memory piece, it does have leading zeroes, but the underlying processing throw these zeroes away, because this is how we understand numbers.
i'm doing some exercises in my Java book. I'm very new to programming. Therefore, notice (in the code) that i'm still on Chapter one. Now I already did everything, I just want a confirmation if this is legitimate so I can feel free to move on next.
If not, I would sincerely appreciate to not do my code for me; I want advice.
Here's the question written in the book,
"Write an application that prompts/reads the numerator and denominator of a fraction as integers, then prints the decimal equivalent of the fraction."
I'll illustrate this sentence with my code:
I did a revision here. Is this one OK?..
import java.util.*;
public class ExerciseEleven {
public static void main (String[] args) {
Scanner sc = new Scanner (System.in);
double fraction;
int fractionValue;
int decimal;
double value;
System.out.println("Enter Numerator: ");
int numerator = sc.nextInt();
System.out.println("Enter Denominator: ");
int denominator = sc.nextInt();
fraction = (double) numerator / denominator;
fractionValue = (int) (fraction * 10);
decimal = fractionValue % 10;
value = decimal * 0.1;
System.out.println(value);
}
}
It compiles and works fine.
Thank you.
It doesn't do what task says it should. You read doubles instead of integers, and the decimal equivalent is not what you print out. Decimal equivalent for 1/2 is 0.5. And you print 5.
Also, you can pay attention to your code style: variable names are usually written in lowerCamelCase, like that : simpleVariable.
Update
now it prints what you need. However you do it not in the very right way and your indentation can still be improved.
It's fine (I didn't read the assignment very well, did I? Kudos to Vladimir.) ...but some comments:
Usually you want to indent methods within the class.
Standard practice is to use initial caps (Numerator) only for types (e.g., classes, interfaces, enums). Variable, field, and method names should start with a lower-case letter. Now, you're free to ignore standard practice, but if you do people will have a lot of trouble reading your code. :-)
For rounding, you probably want to look at Math.round rather than truncating with a cast. But the assignment didn't say anything about rounding.
You might want to handle the case where denominator is zero.
So keeping those in mind:
import java.util.*;
public class ExcerciseEleven {
public static void main (String[] args) {
Scanner sc = new Scanner (System.in);
System.out.println("Enter Numerator: ");
int numerator = sc.nextInt();
System.out.println("Enter Denominator: ");
int denominator = sc.nextInt();
if (denominator == 0) {
System.out.println("Can't divide by zero");
}
else {
double fraction = (double)numerator / denominator;
System.out.println(fraction);
}
}
}
Hey I am doing some thinking about this and I have noticed something interesting after looking at this source and here is the Algorithm that I plan on implementing
First I will convert the number from the Metric using the
Javax.Measure family of functions and I will get a number like
0.3750
Then I will divide the number by ONE_SIXTEENTH which = 0.0625
ONE_SIXTEENTH = 0.0625
The answer 0.3750 / ONE_SIXTEENTH = 6;
So now I know there are 6 sixteenths of the inch
Next I check to see if 6 is divisible by 4, 6/4 = 1.5 ie not a whole number so the fraction is still regarded as 6/16th of an inch for now
Next I check to see if 6 is divisible by 2, 6/2 = 3
This is a whole number so we will use it to reconstitute the fraction
So now that we have divided 6 by 2 and gotten 3 the 16 needs to be divided by 2 and we end up with 8 so 6/16th of an inch becomes 3/8th of an inch.
PS Has anyone noticed that this is similar to a fizz bang program?
____________________________________________
Here is the chart which helped me get my head around this
My workings
There are three important parts of division operation :
Sign of the result.
Integral part
Decimal part
Also, there are few corner cases where you need to deal with the fact that Integer.MIN_VALUE is greater than Integer.MAX_VALUE when compared in absolute form.
For example : -2147483648/-1 can't yield 2147483648 when divided in the form of integer types. The reason is simple. The type of the resulting type will be integer type, and the maximum positive value that a integer type variable can hold is +2147483647
To mitigate that scenario, we should at first convert both the numerator and denominator into their long positive form. That gives us the integral part of the answer.
The XOR of two numbers will have the sign bit as 1 only in case they have opposite signs. That solves the first part (sign of result) of the problem.
For decimal part, we can employ the general division rule i.e. multiply the remainder with 10 and try dividing again and repeat. Keep record of the remainder we have already come across to prevent the loop from going into unbounded iterations.
public String fractionToDecimal(int A, int B) {
StringBuilder sb = new StringBuilder((A^B) < 0 ? "-" : "");
long a = Math.abs((long)A);
long b = Math.abs((long)B);
sb.append(Long.toString(a/b));
long rem = a % b;
sb.append((rem != 0) ? "." : "");
Map<Long, Integer> remainderMap = new HashMap<>();
int pos = 0;
while (rem != 0){
sb.append(Long.toString((rem*10)/b));
remainderMap.put(rem, pos++);
rem = (rem*10) % b;
if (remainderMap.containsKey(rem)){
String currNum[] = sb.toString().split("\\.");
return currNum[0] + "." + currNum[1].substring(0, remainderMap.get(rem)) +
"(" + currNum[1].substring(remainderMap.get(rem)) + ")";
}
}
if (sb.toString().equals("-0")) return "0";
return sb.toString();
}
Sample output :
2/3 gives 0.(6)
-2147483648/-1 gives 2147483648
I want to generate a random number of 14 positive digits only and I use the below function for it:
public void random()
{
Random number = new Random();
long l = number.nextLong();
number.setSeed(System.currentTimeMillis());
long num = Math.abs(number.nextInt())%999 + (l/100000); // problematic line
mTextBox.setString("" + num);
}
I very new to to JavaMe, I have made above function myself but I believe it is not working as expected. It also generates -ve numbers. Also sometimes one or two digits are missing in generated number resulting in 12 or 13 numbers not 14.
Any suggestions or improvement to the code will be highly appreciated.
If you want 14 digits, then you should use 14 calls to number.nextInt(10) - something like this:
public static String randomDigits(Random random, int length)
{
char[] digits = new char[length];
// Make sure the leading digit isn't 0.
digits[0] = (char)('1' + random.nextInt(9);
for (int i = 1; i < length; i++)
{
digits[i] = (char)('0' + random.nextInt(10));
}
return new String(digits);
}
Note that I've made the instance of Random something you pass in, rather than created by the method - this makes it easier to use one instance and avoid duplicate seeding. It's also more general purpose, as it separates the "use the string in the UI" aspect from the "generate a random string of digits".
I don't know whether Random.nextInt(int) is supported on J2ME - let me know if it's not. Using Math.abs(number.nextInt())%999 is a bad idea in terms of random distributions.
I didn't understand what you really want, the code suggests that you want a 3 digit number (%999).
Otherwise you can create a 14 digit number between 1000000000000000 and 9999999999999999 by
long num = 1000000000000000L + (long)(number.nextDouble() * 8999999999999999.0);
note (1 / 100000) is 0 (zero) since it is done by integer division, use (1.0 / 100000.0) for double division
long num = 10000000000000L+(long)(random.nextDouble()*90000000000000.0);
EDIT:
mTextBox.setString(MessageFormat.format("{0,number,00000000000000}",
new Object[] {new Long(num)}));
You are getting negative numbers because Random.nextInt() returns any 32-bit integer, and half of them are negative. If you want to get only positive numbers, you should use the expression Random.nextInt() & 0x7fffffff or simply Random.nextInt(10) for a digit.