I want to split a 4-digit integer in to 2. i.e convert 1234 into two variables; x=12 and y=34. Using Java.
int four = 1234;
int first = four / 100;
int second = four % 100;
the first one works because integers are always rounded down, stripping the last two digits when divided by 100.
the second one is called modulo, dividing by 100 and then taking the rest. this strips all digits exept the first two.
Lets say you have a variable number of digits:
int a = 1234, int x = 2, int y = 2;
int lengthoffirstblock = x;
int lengthofsecondblock = y;
int lengthofnumber = (a ==0) ? 1 : (int)Math.log10(a) + 1;
//getting the digit-count from a without string-conversion
How can I count the digits in an integer without a string cast?
int first = a / Math.pow(10 , (lengthofnumber - lengthoffirstblock));
int second = a % Math.pow(10 , lengthofsecondblock);
and at the end something usefull if you have cases where the input could be negative:
Math.abs(a);
int a = 1234;
int x = a / 100;
int y = a % 100;
int i = 1234;
int x = 1234 / 100;
int y = i - x * 100;
You can treat it as a string and split it using substring(), or as an integer:
int s = 1234;
int x = s / 100;
int y = s % 100;
If it's originally an int, I'd keep it as an int and do the above.
Note that you need to consider what happens if your input is not four digit. e.g. 123.
In case you want to split the same no:
int number=1234;
int n,x,y; //(here n=1000,x=y=1)
int f1=(1234/n)*x; //(i.e. will be your first splitter part where you define x)
int f2=(1234%n)*y; //(secend splitter part where you will define y)
If you want to split the number in (12*x,34*y){where x=multiple/factor of 12 & y=multiple/factor of 34),then
1234=f(x(12),y(34))=f(36,68)
int number=1234;
int n; //(here n=1000)
int x=3;
int y=2;
int f1=(1234/n)*x; //(i.e. will be your first splitter part where you define x)
int f2=(1234%n)*y; //(secend splitter part where you will define y)
int i = 1234;
int x = i / 100;
int y = i % 100;
int num=1234;
String text=""+num;
String t1=text.substring(0, 2);
String t2=text.substring(2, 4);
int num1=Integer.valueOf(t1);
int num2=Integer.valueOf(t2);
System.out.println(num1+" "+num2);
Related
I am trying to write a program that receives from the user two numbers. one (x) is a number between 0 - 9 and the second (y) is any natural number. the problem is that I want to check how many times x is in y for example: if x = 2 and y = 2245 then the output would be 2
int x = 3;
int y = 233457693;
int total = 0;
String[] ys = String.valueOf(y).split("");
for (String s : ys) {
if (s.equals(String.valueOf(x))) total++;
}
System.out.println(total);
prints 3
My trick is to transform int in String, after find with Matcher class and count how many String x are in the String y.
So, I try something like that and it's worked:
int x = 2;
int y = 2245;
Pattern pattern = Pattern.compile(x + ""); //Create the pattern with the x number
Matcher matcher = pattern.matcher(y + ""); //Create the matcher wtih de pattern and insert y in string
int c = 0;
while (matcher.find()) c++; //Count the matches
System.out.println(c); //Print
Ouput:
2
Here is solution for Java 8 and higher using Stream:
int x = 2;
int y = 2245;
long count = String.valueOf(y).chars().filter(ch -> ch == Character.forDigit(x,10)).count();
You can convert x and y to String and use charAt() method.
int x = 2;
int y = 2245;
int counter = 0;
String xString = String.valueOf(x);
String yString = String.valueOf(y);
for(int i=0; i<yString.length(); i++)
{
if(yString.charAt(i)==xString.charAt(0))
counter++;
}
System.out.println(counter);
I have an integer in java "1234567" and my program finds middle digit in a set of integer, is there more optimized way than below code?. Recently asked in java interview.
What I have done is first find no of digits, first, last and middle indexes. Then find middle digit again iterating on same integer. Please advice some optimization.
int a1 = 1234567;
int a = a1;
// calculate length
int noOfDigits = 0;
while(a!=0)
{
a = a/10;
noOfDigits++;
}
int first = 0;
int last = noOfDigits-1;
int middle = (first+last)/2;
boolean midExists = ((a1%2)==1);
System.out.println(" digits: "+a1);
System.out.println(" no of digits "+noOfDigits);
System.out.println(" first "+first);
System.out.println(" last " + last);
if(midExists)
{
System.out.println(" middle " + middle);
int i = last;
int middleDigit = 0;
a = a1;
while(i != middle)
{
a = (a / 10);
middleDigit = (a%10);
i--;
}
System.out.println("middle digit: " + middleDigit);
}
else
System.out.println(" Mid not Exists.. ");
Program Output:
digits: 1234567
no of digits 7
first 0
last 6
middle 3
middle digit: 4
You can also do this in one pass. Idea is that first store the integer in the another variable. Then move two digits to the left in one integer while only one digit in the another one.
int a1 = 1234567;
int a2 = a1;
int flag=0;
while(a2>0)
{
a2/=10; //Moves to the left by one digit
if(a2==0) //If there are odd no. of digits
{
flag=1;
break;
}
a2/=10; //Moves to the left by one digit
a1/=10; //Moves to the left by one digit
}
System.out.print(flag!=1?"No Mid Exists":a1%10);
Your "math" is working correctly. The one thing you can: compute the length (number of digits) within your number upfront, to avoid "iterating" the number twice - so you can determine if that number of digits is even or odd without "iterating" the number:
int n = 1234;
int length = (int)(Math.log10(n)+1);
should give you 4 for 1234, and 5 for 12345.
But beyond that: you can express information in different ways. For example: you can turn an int value into a string.
String asStr = Integer.toString(123456);
And now: you can easily check the length of that string; and you can directly access the corresponding character!
The only thing to keep in mind: characters representing numbers like '1', '2', ... have different numerical values as int 1, 2, ... (see an ASCII table; as '1' is 49 when regarding its numerical value)!
this answer has less code, but wouldn't take much in performance i think:
int a1 = 12334;
int a = a1;
int middle = 0;
int noOfDigits = 0;
while (a1 != 0) {
a1 = a1 / 10;
noOfDigits++;
}
if (noOfDigits % 2 == 1) {
for (int i = 0; i < (noOfDigits / 2) + 1; i++) {
middle = a % 10;
a = a / 10;
}
System.out.println(middle);
} else {
System.out.println("No mid existing");
}
Using only math
int num = 123406789;
int countDigits = (int)Math.ceil(Math.log10(num));
int midIndex = (int)Math.ceil(countDigits/2);
int x = num / (int)Math.pow(10, midIndex);
int middleDigit = x % 10;
System.out.println(middleDigit);
I'm trying to implement Karatsuba multiplication through recursive calls. The code below should work, but I keep getting the wrong answer. Any thoughts?
public static long karatsuba(long x, long y){
//base case:
if (x < 10 || y < 10) return x * y;
//length of digits:
int xSize = String.valueOf(x).length();
int ySize = String.valueOf(y).length();
int N = Math.max(xSize, ySize);
//split each number in half (by length of digits):
long numX_hi = Long.valueOf((String.valueOf(x).substring(0, N/2)));
long numX_lo = Long.valueOf((String.valueOf(x).substring(N/2, xSize)));
long numY_hi = Long.valueOf((String.valueOf(y).substring(0, N/2)));
long numY_lo = Long.valueOf((String.valueOf(y).substring(N/2, ySize)));
//solve multiplications recursively:
long z0 = karatsuba(numX_lo,numY_lo);
long z1 = karatsuba((numX_hi+numX_lo),(numY_hi+numY_lo));
long z2 = karatsuba(numX_hi,numY_hi);
//answer:
return (long)(z2 * Math.pow(10,N)) + (long)((z1-z2-z0) * Math.pow(10,(N/2))) + (z0);
}
Here are a few test cases:
1) karatsuba(1234,5678) >>> 6952652
*should be 7006652
2) karatsuba(4589, 7831) >>> 34649459
*should be 35936459
3) karatsuba(911, 482) >>> 44722
*should be 472842
There are two distinct problems with your method.
Firstly, you should split starting from the last (least significant) digit, not the first. So if you've got these two numbers:
1234
567890
You currently split them like this:
123 4 (123*1000+4)
567 890 (567*1000+890)
This gets you the wrong result because 1234 != 123*1000+4
You should instead split them like this:
1 234 (1*1000+234)
567 890 (567*1000+890)
The second error I discovered happens when you add things back together.
return (long)(z2 * Math.pow(10,N)) + (long)((z1-z2-z0) * Math.pow(10,(N/2))) + (z0);
Will return an incorrect result for odd Ns, as N/2 will be rounded up down and therefore N != ((N/2)*2)
I've combined the two fixes and now I get the correct results:
public static long karatsuba(long x, long y){
//base case:
if (x < 10 || y < 10) return x * y;
//length of digits:
int xSize = String.valueOf(x).length();
int ySize = String.valueOf(y).length();
int halfN = Math.max(xSize, ySize) / 2; // store N/2 instead of N
int splitX = xSize - halfN; // count the split point from xSize down
int splitY = ySize - halfN; // count the split point from ySize down
//split each number in half (by length of digits):
long numX_hi = Long.valueOf((String.valueOf(x).substring(0, splitX)));
long numX_lo = Long.valueOf((String.valueOf(x).substring(splitX)));
long numY_hi = Long.valueOf((String.valueOf(y).substring(0, splitY)));
long numY_lo = Long.valueOf((String.valueOf(y).substring(splitY)));
//solve multiplications recursively:
long z0 = karatsuba(numX_lo,numY_lo);
long z1 = karatsuba((numX_hi+numX_lo),(numY_hi+numY_lo));
long z2 = karatsuba(numX_hi,numY_hi);
//answer:
return (long)(z2 * Math.pow(10,halfN*2)) + (long)((z1-z2-z0) * Math.pow(10,halfN)) + (z0);
}
The accepted solution gives a StringIndexOutOfBoundsException if the length of one number string is more than twice the other, because the splitX or splitY would be negative.
To prevent this problem, one must catch this exception and then set halfN to be Math.min(xSize, ySize)/2 . Here is the corrected code:
public static long karatsuba(long x, long y){
//base case:
if (x < 10 || y < 10) return x * y;
//length of digits:
int xSize = String.valueOf(x).length();
int ySize = String.valueOf(y).length();
int halfN = Math.max(xSize, ySize) / 2; // store N/2 instead of N
if (halfN >= xSize || halfN >= ySize){
halfN = Math.min(xSize, ySize) / 2; // prevents string index error
}
int splitX = xSize - halfN; // count the split point from xSize down
int splitY = ySize - halfN; // count the split point from ySize down
//split each number in half (by length of digits):
long numX_hi = Long.valueOf((String.valueOf(x).substring(0, splitX)));
long numX_lo = Long.valueOf((String.valueOf(x).substring(splitX)));
long numY_hi = Long.valueOf((String.valueOf(y).substring(0, splitY)));
long numY_lo = Long.valueOf((String.valueOf(y).substring(splitY)));
//solve multiplications recursively:
long z0 = karatsuba(numX_lo,numY_lo);
long z1 = karatsuba((numX_hi+numX_lo),(numY_hi+numY_lo));
long z2 = karatsuba(numX_hi,numY_hi);
//answer:
return (long)(z2 * Math.pow(10,halfN*2)) + (long)((z1-z2-z0) * Math.pow(10,halfN)) + (z0);
}
If a user enters a value for
x y and z coordinates, what steps would need to take in order to create a range from -x/y/z to +x/y/z? Is there a function that will give the numbers in that range even though a double is entered?
This is my code so far im not finished yet, I'm not sure if its right. After it gets the x,y,z points and the number of data points the user wants, it will then print the n number of points with random points (x , y, z) x, y, z being anywhere from -x to x etc.
import java.io.*;
public class MultiDimArray
{
public static void main (String [] args) throws IOException
{
BufferedReader myInput = new BufferedReader (new InputStreamReader (System.in));// Buffered Reader reads the number inputed
double range;
System.out.println("How many points do you want returned? ");
String numPointsA = myInput.readLine();
int numPoints = Integer.parseInt(numPointsA);
System.out.println("Enter X length: ");
String xlengthA = myInput.readLine();
double xlength = Double.parseDouble(xlengthA);
System.out.println("Enter Y length: ");
String ylengthA = myInput.readLine();
double ylength = Double.parseDouble(ylengthA);
System.out.println("Enter Z length: ");
String zlengthA = myInput.readLine();
double zlength = Double.parseDouble(zlengthA);
int[][][][] dataPoint = new int[3][xlength][ylength][zlength];
for (int i = 0; i < (xlength * 2); i++){
range = (0 -( xlength - i) + 1);
System.out.println(range);
}
for (int i = 0; i < (ylength * 2); i++){
range = (0 -( ylength - i) + 1);
}
for (int i = 0; i < (zlength * 2); i++){
range = (0 -( zlength - i) + 1);
}
}
}
range is infinite if you want to include all fractional numbers otherwise you can do that manually.
for (int i=-x; i<=x; i++)
operate(i, y, z);
another solution for your problem is that you don't generate range.
you just store those values x y and z.
then, when you need to test if a number is in range you can do it easily with if statement.
what I mean that this a wrong way to design your solution. try to get values you want in another way. something like reverse engineering. then you test if those values are in range.
post your problem. then we can help you.
Code that generates numPointsA random numbers between -x and x:
Random random = new Random();
double start = -x;
double end = x;
for (int i=0;i<numPointsA;i++)
{
double ran = random.nextDouble();
double result = start + (ran * (end - start));
System.out.println(result);
}
To get a random number between 0 and n-1, use
Random rand = new Random();
int r = rand.nextInt(n);
This is a homework problem
How would I reverse an integer in Java with a for loop? The user will input the integer (I don't know how long it will be) and I need to reverse it. ie: If they enter 12345, my program returns 54321.
Here's the catch, you can't use String, StringBuffer, arrays, or other advanced structures in this problem.
I have a basic idea of what I need to do. My problem is...in the for loop, wouldn't the condition need to be x < the length of the integer (number of digits)? How would I do that without String?
Thanks for any input, and I'll add more information if requested.
EDIT:
Of course, after introspection, I realized I should use another for loop to do this. What I did was create a for loop that will count the digits by dividing by 10:
int input = scan.nextInt();
int n = input;
int a = 0;
for (int x = 0; n > 0; x++){
n = n/10;
a = a + 1;
}
EDIT 2:
This is what I have
int input = scan.nextInt();
int n = input;
int a = 0;
int r = 0;
for (int x = 0; n > 0; x++){
n = n/10;
a = a + 1;
}
for (int y = 0; y < n; y++) {
r = r + input%10;
input = input/10;
}
System.out.println(input);
When I run it, it isn't reversing it, it's only giving me back the numbers. ie: if I put in 1234, it returns 1234. This doesn't make any sense to me, because I'm adding the last digit to of the input to r, so why wouldn't it be 4321?
While your original number is nonzero, take your result, multiply it by 10, and add the remainder from dividing the original by 10.
For example, say your original number is 12345. Start with a result of 0.
Multiply result by 10 and add 5, giving you 5. (original is now 1234.)
Multiply result by 10 and add 4, giving you 54. (original is now 123.)
Multiply result by 10 and add 3, giving you 543. (original = 12.)
Multiply result blah blah 5432. (original = 1.)
Multiply, add, bam. 54321. And 1 / 10, in int math, is zero. We're done.
Your mission, should you choose to accept it, is to implement this in Java. :) (Hint: division and remainder are separate operations in Java. % is the remainder operator, and / is the division operator. Take the remainder separately, then divide the original by 10.)
You will need to use math to access each of the digits. Here's a few hints to get your started:
Use the % mod operator to extract the last digit of the number.
Use the / division operator to remove the last digit of the number.
Stop your loop when you have no more digits in the number.
This might not be the proper way but
public static int reverseMe(int i){
int output;
String ri = i + "";
char[] inputArray = ri.toCharArray();
char[] outputArray = new char[inputArray.length];
for(int m=0;m<inputArray.length;m++){
outputArray[inputArray.length-m-1]=inputArray[m];
}
String result = new String(outputArray);
output = Integer.parseInt(result);
return output;
}
public static void reverse2(int n){
int a;
for(int i = 0; i < n ; i ++){
a = n % 10;
System.out.print(a);
n = n / 10;
if( n < 10){
System.out.print(n);
n = 0;
}
}
}
here is the Answer With Correction of Your Code.
import static java.lang.Math.pow;
import java.util.*;
public class MyClass {
public static void main(String args[]) {
Scanner scan=new Scanner(System.in);
int input = scan.nextInt();
int n = input;
int a = 0;
int r = 0;
for (; n > 0;){
n = n/10;
a = a + 1;
}
for (int y = 0; y < input;a--) {
r =(int)( r + input%10*pow(10,a-1));
input = input/10;
}
System.out.println(r);
}
}