I am trying to implementing Karatsuba's algorithm from wikipedia and I cannot continue to code since I do not know to how to split an integer into lower-half and upper-half. For example, if we have an integer 223, then it should be split into two integer 22 and 3.
How I might do this?
so it has to be something like
num1 = 223;
some magical stuff happening here!
low1 = 22;
low2 = 3;
Thank you very much I really appreciate your help!
low1 = num1 / 10;
low2 = num1 % 10;
This is the gist of what you're trying to accomplish. I'm not familiar with the algorithm and what exactly you're trying to do, so extra logic will almost certainly be required, but this is a good starting point.
You can use the modulus (%) operator to extract digits from a number. For example
12345 % 10 = 5
12345 % 100 = 45
12345 % 1000 = 345
And so on. Hope this helps.
you can use the modulus (%) operator to remove out the last number of an integer
int num1 = 223;
int num2 = num1%10;
num2 = 3 in this case
I would suggest this algorithm to split an integer :
int i = 233678546; /* The integer you would like to split */
int digitNumber = String.valueOf(i).length(); /* use java.math.Math.log10 if you need a more mathematical approach */
double val = Math.pow(10.0, (double)(digitNumber / 2));
int div = new Double(val).intValue();
int left = i / div;
int right = i % div;
StringBuilder sb = new StringBuilder();
sb.append("Value : ");
sb.append(i);
sb.append('\n');
sb.append("Left : ");
sb.append(left);
sb.append('\n');
sb.append("Right : ");
sb.append(right);
sb.append('\n');
System.out.println(sb.toString());
Related
How can I reorder numbers in a int number to get minimum value.
Ex:
I input a number: $71440 and I want my output is: $1447 (this is minimum value after reordering). I think I will spits the numbers in my input number first like this , after that I will reorder them. That is good algorithm?
Yes it is good if you
split by digit
sort digits
make number out of those digits
What you need is essentially a sorting of the digits of the number. So yes, your proposed method will work and it seems as a reasonable practice.
I think this does roughly what you want it to do. Assumes that the input is positive, I'm sure you can figure out how to modify it to work with negative numbers if you need that.
public static int leastValue(int input) {
String s = Integer.toString(input);
char[] c = s.toCharArray();
Arrays.sort(c);
s = new String(c);
return Integer.parseInt(s);
}
The basic idea is:
Turn value into a string
Put each character into an array
Sort the array of characters, in most character sets this will order the numbers from smallest to largest.
Turn it into a string again
Parse it into an int
For readability I think Diasiares answer is better. However a different approach would be something like this. It sorts a long with a "merge sort like" algorithm. To understand how it works please view the gif file from wikipedia
public static long sort(long num) {
long res;
if (num > 9) {
//split num into two parts(n1, n2)
int numberOfDigits = (int) Math.log10(num) + 1;
long n1 = num / (long) Math.pow(10, numberOfDigits / 2);
long n2 = num % (long) Math.pow(10, numberOfDigits / 2);
//sort each part
long s1 = sort(n1);
long s2 = sort(n2);
//merge them into one number
res = merge(s1, s2);
} else {
res = num;
}
return res;
}
/**
* merges two sorted long into on long e.g 149 and 345 will give 134459
*/
public static long merge(long num1, long num2) {
return (num1 == 0 || num2 == 0)
? num1 + num2
: num1 % 10 < num2 % 10
? num2 % 10 + merge(num1, num2 / 10) * 10
: num1 % 10 + merge(num1 / 10, num2) * 10;
}
This question already has answers here:
Java: parse int value from a char
(9 answers)
Closed 6 years ago.
I am fairly new to java, about 3 weeks into my course. In my assignment, I needed to use charAt to separate the string into 14 parts. Now I need to use addition and add these together.
I have tried many times with no success. Every time I add them together and print it out it gives me a number way bigger than it should be.
char num1 = roulette.charAt(0);
char num2 = roulette.charAt(1);
char num3 = roulette.charAt(2);
char num4 = roulette.charAt(3);
char num5 = roulette.charAt(4);
char num6 = roulette.charAt(5);
When I add num1+num2+num3+num4+num5+num6, I get a number way bigger than it should be.
Am I missing something?
This is due to you adding the characters together, they will not turn into the number equivalent automatically. You will need to change them yourself, to do this you can use Integer.parseInt(char) and you can add them together like that. For example Integer.parseInt(String.valueOf('1') + Integer.parseInt(String.valueOf('2')) this will add 1 + 2 together correctly now resulting in 3 rather than appending 2 to the 1 making 12
If you want to add the characters then each character has a character code that will be used. so for example according to the ASCII Table 'a' = 97, 'b' = 98, 'c' = 99; so if you add these together you will get 294. ASCII Table https://www.cs.cmu.edu/~pattis/15-1XX/common/handouts/ascii.html.
However, if each character represents a number and you want to add the numbers then you can do something like this:
char num1 = roulette.charAt(0);
int firstNum = Integer.parseInt(Character.toString(num1));
char num2 = roulette.charAt(1);
int secondNum = Integer.parseInt(Character.toString(num2));
char num3 = roulette.charAt(2);
int thirdNum = Integer.parseInt(Character.toString(num3));
char num4 = roulette.charAt(3);
int fourthNum = Integer.parseInt(Character.toString(num4));
char num5 = roulette.charAt(4);
int fifthNum = Integer.parseInt(Character.toString(num5));
char num6 = roulette.charAt(5);
int sixthNum = Integer.parseInt(Character.toString(num6));
int result = firstNum + secondNum + thirdNum + fourthNum + fifthNum + sixthNum;
You cannot cast your chars to integer first try like this
Integer.parseInt(num1) + Integer.parseInt(num2) +Integer.parseInt(num3)...
and so on.
EDIT
I just learned that you cannot use Integer.parseInt(num1) for Character.
You should cast your chars as below:
char a = '5';
int b = Integer.parseInt(String.valueOf(a));
int c=b+b;
System.out.println(c); //this will give 10
If you add characters to characters, it means you are adding their ascii values. But if you want to add the numeric value which is presented as a Character in the String, then you have to convert the character to integer first. See the example given below.
N.B. when you want to add a sequence of values, use loop.
Example
String roulette = "123456";
int sum = 0;
for (int i = 0; i < roulette.length(); i++) {
sum = sum + roulette.charAt(i);
}
System.out.println("Sum : " + sum);
sum = 0;
for (int i = 0; i < roulette.length(); i++) {
sum = sum + Integer.parseInt(String.valueOf(roulette.charAt(i)));
}
System.out.println("Sum : " + sum);
Output
Sum : 309
Sum : 21
Case 1: sum = sum + roulette.charAt(i);
Adding ascii values of the numbers. So the sum is 309.
ascii_value('1') - 49
ascii_value('2') - 50
...
ascii_value('5') - 53
ascii_value('6') - 54
Sum = 49 + 50 + 51 + 52 + 53 + 54 = 309
Case 2: sum = sum + Integer.parseInt(String.valueOf(roulette.charAt(i)));
Adding the numeric value instead of the ascii values. So the sum is 21.
Sum = 1 + 2 + 3 + 4 + 5 + 6 = 21
1. long number = 564;
2. String str = number+"";
3. char[] num = str.toCharArray();
4. number = number - num[0];
/* The value of number is 511 */
I am trying to subtract the first digit of the number from the number using this piece of code.
During debugging, i found out that the value of num[0] was 53. Can anyone explain what am i missing here.
I would suggest you to change your fourth line to this:
number = number - Long.parseLong(Character.toString(num[0]));
Basically, what is happening here is that I first convert the char (num[0]) to a string, then parsed the string to a long.
ALternatively, you don't even need to convert the string to a char array! Use charAt() to get the char:
number = number - Long.parseLong(Character.toString(str.charAt(0)));
When you are using the binary operator "-" the smaller datatype, in this case char, is promoted to long which returns the ASCII value of num[0] ('5') which is 53. To get the actual face value of num[0] convert it to String and parse it to Long as Sweeper has pointed out.
It just feels wrong to convert a number to a string, extract the first char, convert back to number and subtract. Why don't you extract the first digit while working with numbers directly. Something like this would do:
long number = 564;
int digits = 0;
assert (number > 0);
for (long num = number; num > 1; num = num / 10 ) {
digits += 1;
}
int firstDigit = (int) (number / Math.pow(10, digits -1));
number = number - firstDigit;
System.out.println(number);
If you want to get all digits:
long number = 564;
int digits = 0;
assert (number > 0);
for (long num = number; num > 1; num = num / 10 ) {
digits += 1;
}
for (int digit = digits - 1; digit >= 0; digit--) {
int currentDigit = (int) (number / Math.pow(10, digit)) % 10;
System.out.println(currentDigit);
}
Trying to split a double number into two decimal parts by dot. Like this: 1.9 into 1 and 9; 0.16 into 0 and 16;
Here's what I do, but seems a little redundant, what's the best way to do this?
The origin number will always be like Just 0.x or 1.x or 0.xx or 1.xx and xx > 10
double d = 1.9;
int a, b;
String dString = Double.toString(d);
String aString = dString.substring(0, 1);
String bString = dString.substring(2);
a = Integer.parseInt(aString);
b = Integer.parseInt(bString);
My way of doing this seems using to much String conversion,which I don't think is very efficient.
You can try this way too
double val=1.9;
String[] arr=String.valueOf(val).split("\\.");
int[] intArr=new int[2];
intArr[0]=Integer.parseInt(arr[0]); // 1
intArr[1]=Integer.parseInt(arr[1]); // 9
You could treat the double like a string, and split it on the decimal place.
double d = 13454.92345;
String bob = Double.toString(d);
String[] convert = bob.split("\\.");
int a = Integer.parseInt(convert[0]);
int b = Integer.parseInt(convert[1]);
System.out.println(a); // 13454
System.out.println(b); // 92345
To get the decimal part as an int is not really following any standards, so you are stuck with your special solution for that. Getting the value before the decimal point can be simplified to a simple cast though:
double d = 1.9;
int a, b;
String dString = Double.toString(d);
String bString = dString.substring(2);
a = (int) d;
b = Integer.parseInt(bString);
Note that the substring() and parseInt() fails if the number is 10 or bigger though. You might want to change the substring() call to something like:
String bString = dString.split("\\.")[1];
double num=12.5;
String str=Double.toString(num);
String strarray[]=str.split("\\.");
Now strarray[0] will be holding 12, and strarray[1] will be having 5.You can convert them into integers by writing following code:
int num1=Integer.parseInt(strarray[0]);
int num2=Integer.parseInt(strarray[1]);
double d = 1.9;
String str = Double.toString(d);
String strArray[] = str.split("\\.");
int a = Integer.parseInt(strArray[0]);
int b = Integer.parseInt(strArray[1]);
System.out.print(a + " - " + b);
Try this. This will work.
Here's a two line version:
int a = (int)d;
int b = Integer.parseInt((d + "").split("\\.", 2)[1]).replaceAll("^$", "0"));
The first part is easy - just cast to int, which automatically chops off any decimal part of the number.
The second part is easiest with a Strimg approach - split the string version on a dot and use the second part. Note the addition of "" which generates a string, and the handling of the edge case of there being no decimal part, where 3 as a double prints as 3. - if the result is a blank (guaranteed by the second parameter to split) which is then converted to a zero.
This solution should work for almost any length of the fractional part and doesn't use strings.
For example the accepted answer doesn't work for 0.16
double d = 123.456
long a = (long) d;
double f = d - a;
while (Math.abs((long) f - f) > 0.000001) f *= 10;
long b = (long) f;
// a = 123
// b = 345
Here is another approach:
double d=1.9;
int a;
int b;
a = (int) d/10;
b = (int) d%10;
System.out.print("a");
System.out.print("b");
double dub=1234.5678987;//Variable to be manipulated
long lon=0; //To store before decimal point.
short sh=0;//To store after decimal point.
int deci=10000; //to 4 decimal places
lon=(int)dub;// get the integer part of the number stored in long
sh=(short)((dub-(double)lon)*deci);//deci to required decimal places.
System.out.println(""+lon+"."+sh);
I tried a split on "." and then just parse the string for integers.
String a="";
double x = 2.4;
a=x+"";
String [] v =a.split("\\.");
int before = Integer.parseInt(v[0]);
int after = Integer.parseInt(v[1]);
I am trying to figure out part of a Java assignment and I am lost on what to do. If anyone can help or guide me in the right direction I would really appreciate it!
The user has to enter a six digit "ticket number". I am trying to figure out how to drop the last digit of the number that the user input and place it into it's own variable.
For instance:
Ticket Number: 123456
How do I drop the "6" to make the number "12345" and put the 6 in its own variable?
I tried using the \b to backspace the last digit after turning the input into a string, but that did not work. And I have realized that it would just delete the number anyway if it did work.
Once the last digit is dropped we have to do calculations to get a remainder... I'm not worried about that, I have found that described in our book, I just can't figure out how to drop the digit and put it by itself.
I am very new to Java (this is a Chapter 2 assignment) so please go easy on me!
Thank you everyone for your help. I appreciate it!
This is what I came up with and the code works:
import javax.swing.JOptionPane;
public class TicketNumber
{
public static void main(String[] args)
{
String ticketNumber;
int Ticket, Remainder, lastDigit;
ticketNumber = JOptionPane.showInputDialog(null,
"Enter the six digit ticket number",
"Verify Ticket", JOptionPane.INFORMATION_MESSAGE);
Ticket = Integer.parseInt(ticketNumber) / 10;
lastDigit = Integer.parseInt(ticketNumber) % 10;
Remainder = Ticket % 7;
boolean Valid = lastDigit == Remainder;
JOptionPane.showMessageDialog(null, "Valid Ticket" + "\n" + Valid);
}
}
It depends on what data type you are working with. If the value is a String, you can use the substring method:
String ticket = "123456";
String allButLast = ticket.substring(0, ticket.length() - 1); // becomes "12345"
If it is an int value, you can use integer division:
int ticket = 123456;
int allButLast = ticket / 10; // truncates to 12345
If it's a float or double, you can divide by 10 and cast to an int or you can use Math.floor() to drop the fractional part after dividing by 10.
EDIT: Based on the edit to your question, you can do this:
public class TicketNumber
{
public static void main(String[] args)
{
String ticketNumber;
int ticket, prefix, remainder, lastDigit;
ticketNumber = JOptionPane.showInputDialog(null,
"Enter the six digit ticket number",
"Verify Ticket", JOptionPane.INFORMATION_MESSAGE);
ticket = Integer.parseInt(ticketNumber);
prefix = ticket / 10;
lastDigit = ticket % 10;
remainder = prefix % 7;
boolean valid = lastDigit == remainder;
JOptionPane.showMessageDialog(null, "Valid Ticket" + "\n" + valid);
}
}
Note that Ticket, etc. are not good Java variable names; they should start with lower-case letters (e.g., ticket). I made that change in my version of the code.
Note that the calculation can be written more tersely as:
boolean valid = (ticket % 10) == ((ticket / 10) % 7);
and you can eliminate the variables prefix, remainder, and lastDigit.
You can use modulo operator % and division operator /
int number = 123456;
int remainder = 123456 % 10;
int newNumber = 123456 / 10;
System.out.println(newNumber); // output is 12345
System.out.println(remainder); // output is 6
int n=123456,m=n/10;
System.out.println("Number = "+m);//your code
Your Output:-
Number = 12345