I'm writing a code for an assignment for school but it requires me to compare two int values. For example, if you have the number 123 and the other number is 321, they have the same digits but are in different orders. Is there easy way of comparing them or do i have to make them into a string and compare them as string types? if its the latter, how could i compare two strings? Is there any way of doing this without an array?
By comparing int values, if you mean greater than, less than or equal you can do that like so.
int a = 123, b= 321;
if(a > b)
//a is greater than b (b is less than a)
if(a == b)
// a is equal to b
if(a < b)
// a is less than b (b is greater)
Could use some clarification, if you want to check if the number is reversed like you said in an example its called a palindrome.
You could reverse a number in the following if you had experience with loops and modulo(the %) in the following snippet.
int r = 0;
while(number != 0){
r = r * 10 + number % 10;
number /= 10; }
return r;
r would be that number reversed. If you input let's say 123 you would get 321 back, then you could compare it to the other to see if its just the reverse.
Let me know if you have any more questions and I'll try to answer!
To check if a number is arbitrarily mixed and not reversed to winning number, you could try the following.
Two numbers a and b, a is the winning number and b is the number the user chose.
a is 251 and b is 521.
You could do this on each number to separate them.
int p1,p2,p3;
p1 = num % 10;
p2 = num / 10 % 10;
p3 = num / 100 % 10;
This would separate ex. 251 into 2, 5, and then 1. Then you could add them as so doing the same process for the second. sum is p1 + p2 + p3 and sum2 is p4 + p5 + p6 for the second number. Provided the numbers are not reversed. Use the thing I mentioned before for that case to check if they are flipped.
if(sum == sum2)
//Numbers are mixed but you won!
This should work.
Certainly not the fastest solution, but the code is short and easy to understand.
public boolean arePalindromes(int a, int b){
//convert them to char arrays for easy sorting
char[] aryA = String.valueOf(a).toCharArray();
char[] aryB = String.valueOf(b).toCharArray();
//sort them
Collections.sort(aryA);
Collections.sort(aryB);
//put them back to strings for easy comparison
String strA = new String(aryA);
String strB = new String(aryB);
//compare
return strA.equals(strB);
}
Please try the following code (I have tested it), of which idea is borrowed from here and here. This solution still uses array.
public class CompareInt {
public static void main(String[] args) {
System.out.println(containSameDigits(123, 123));
System.out.println(containSameDigits(123, 321));
System.out.println(containSameDigits(123, 132));
System.out.println(containSameDigits(123, 323));
System.out.println(containSameDigits(123, 124));
System.out.println(containSameDigits(123, 111));
}
public static boolean containSameDigits(int x, int y) {
String xSorted = getSortedString(x);
String ySorted = getSortedString(y);
return xSorted.equalsIgnoreCase(ySorted);
}
public static String getSortedString(int x) {
String xSorted = "";
for (int digit = 0; digit < 9; digit++) {
for (int temp = x; temp > 0; temp /= 10) {
if (temp % 10 == digit) {
xSorted += digit;
}
}
}
return xSorted;
}
}
Output:
true
true
true
false
false
false
Related
I have got a little problem—I need to prepare program that (step by step information):
1)Gets from user two integers a and b and stop when b>a
2)Sum the products off all numbers in range < a, b > that digits are prime numbers
Example:
Input: 10, 15,
Output: 2340
(because 12*13*15 = 2340
2, 3 and 5 are prime numbers)
I feel like I stuck—I have got only a sum of the numbers (not the product) and not the prime but all of them.
public class Ex4 {
static int getNmbs() {
System.out.println("Enter number:");
Scanner sc = new Scanner(System.in);
return sc.nextInt();
}
public static int getSum(int a, int b) {
if (a > b)
return 0;
else
return a + getSum(a + 1, b);
}
public static void main(String[] args) {
int a = getNmbs();
int b = getNmbs();
int c =getSum(a,b);
System.out.println(c);
}
}
In order to solve this problem, you need to think of the step by step process:
First, accept two integer inputs, a and b.
Declare a variable to hold your product (the answer) and initialize it at 1. (If you initialize it at 0, then you will always get 0)
Now, assuming a < b, check to see if the digits of a are prime. IF it is, multiply your product by it and increment a. If it isn't, just increment a.
Rinse and repeat until a > b. And return the final product.
The trick here is going to be figuring out a way to check if the digits of a number are prime. I suggest using modulo division in increments of powers of 10 (for those more mathematically inclined) or converting the integer to a String and checking each character (using toCharArray).
Hope this helps!
This is a non recursive approach.
static boolean isProductPrime(int num){
int tmp = num % 10;
if( tmp < 2) return false;
for(int i = 2; i*i <= tmp; i++) //Instead of Math.SQRT
if(tmp % i == 0) return false;
return true;
}
public static void main(String [] args) {
Scanner myScanner = new Scanner(System.in);
int a = myScanner.nextInt();
int b = myScanner.nextInt();
int ans = 1;
for(int i = a ; i <= b ; i++){
if(isProductPrime(i))
ans *=i;
}
if( b < a)
ans = 0;
System.out.println(ans);
}
I am trying to add two binary numbers and then get their sum in binary system. I got their sum in decimal and now I am trying to turn it into binary. But there is problem that when I take their sum (in decimal) and divide by 2 and find remainders(in while loop), I need to put remainders into array in order print its reverse. However, there is an error in array part. Do you have any suggestions with my code? Thanks in advance.
Here is my code:
import java.util.Scanner;
public class ex1 {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int n = scan.nextInt();
int m = scan.nextInt();
int k = dec1(n)+dec2(m);
int i=0,c;
int[] arr= {};
while(k>0) {
c = k % 2;
k = k / 2;
arr[i++]=c; //The problem is here. It shows some //error
}
while (i >= 0) {
System.out.print(arr[i--]);
}
}
public static int dec1(int n) {
int a,i=0;
int dec1 = 0;
while(n>0) {
a=n%10;
n=n/10;
dec1= dec1 + (int) (a * Math.pow(2, i));
i++;
}
return dec1;
}
public static int dec2(int m) {
int b,j=0;
int dec2 = 0;
while(m>0) {
b=m%10;
m=m/10;
dec2= dec2 + (int) (b * Math.pow(2, j));
j++;
}
return dec2;
}
}
Here:
int[] arr= {};
creates an empty array. Arrays don't grow dynamically in Java. So any attempt to access any index of arr will result in an ArrayIndexOutOfBounds exception. Because empty arrays have no "index in bounds" at all.
So:
first ask the user for the count of numbers he wants to enter
then go like: int[] arr = new int[targetCountProvidedByUser];
The "more" real answer would be to use List<Integer> numbersFromUsers = new ArrayList<>(); as such Collection classes allow for dynamic adding/removing of elements. But for a Java newbie, you better learn how to deal with arrays first.
Why are you using two different methods to do the same conversion? All you need is one.
You could have done this in the main method.
int k = dec1(n)+dec1(m);
Instead of using Math.pow which returns a double and needs to be cast, another alternative is the following:
int dec = 0;
int mult = 1;
int bin = 10110110; // 128 + 48 + 6 = 182.
while (bin > 0) {
// get the right most bit
int bit = (bin % 10);
// validate
if (bit < 0 || bit > 1) {
throw new IllegalArgumentException("Not a binary number");
}
// Sum up each product, multiplied by a running power of 2.
// this is required since bits are taken from the right.
dec = dec + mult * bit;
bin /= 10;
mult *= 2; // next power of 2
}
System.out.println(dec); // prints 182
An alternative to that is to use a String to represent the binary number and take the bits from the left (high order position).
String bin1 = "10110110";
int dec1 = 0;
// Iterate over the characters, left to right (high to low)
for (char b : bin1.toCharArray()) {
// convert to a integer by subtracting off character '0'.
int bit = b - '0';
// validate
if (bit < 0 || bit > 1) {
throw new IllegalArgumentException("Not a binary number");
}
// going left to right, first multiply by 2 and then add the bit
// Each time thru, the sum will be multiplied by 2 which shifts everything left
// one bit.
dec1 = dec1 * 2 + bit;
}
System.out.println(dec1); // prints 182
One possible way to display the result in binary is to use a StringBuilder and simply insert the converted bits to characters.
public static String toBin(int dec) {
StringBuilder sb = new StringBuilder();
while (dec > 0) {
// by inserting at 0, the bits end up in
// correct order. Adding '0' to the low order
// bit of dec converts to a character.
sb.insert(0, (char) ((dec & 1) + '0'));
// shift right for next bit to convert.
dec >>= 1;
}
return sb.toString();
}
I'm trying to write a method that will calculate if two numbers are relatively prime for an assignment. I'm primarily looking for answers on where to start. I know there is a method gcd() that will do a lot of it for me, but the assignment is pretty much making me do it without gcd or arrays.
I kind of have it started, because I know that I will have to use the % operator in a for loop.
public static boolean relativeNumber(int input4, int input5){
for(int i = 1; i <= input4; i++)
Obviously this method is only going to return true or false because the main function is only going to print a specific line depending on if the two numbers are relatively prime or not.
I'm thinking I will probably have to write two for loops, both for input4, and input5, and possibly some kind of if statement with a logical && operand, but I'm not sure.
Well in case they are relatively prime, the greatest common divider is one, because - if otherwise - both numbers could be devided by that number. So we only need an algorithm to calculate the greatest common divider, for instance Euclid's method:
private static int gcd(int a, int b) {
int t;
while(b != 0){
t = a;
a = b;
b = t%b;
}
return a;
}
And then:
private static boolean relativelyPrime(int a, int b) {
return gcd(a,b) == 1;
}
Euclid's algorithm works in O(log n) which thus is way faster than enumerating over all potential divisors which can be optimized to O(sqrt n).
Swift 4 code for #williem-van-onsem answer;
func gcd(a: Int, b: Int) -> Int {
var b = b
var a = a
var t: Int!
while(b != 0){
t = a;
a = b;
b = t%b;
}
return a
}
func relativelyPrime(a : Int, b: Int) -> Bool{
return gcd(a: a, b: b) == 1
}
Usage;
print(relativelyPrime(a: 2, b: 4)) // false
package stack;
import java.util.Scanner; //To read data from console
/**
*
* #author base
*/
public class Stack {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
Scanner in = new Scanner(System.in); // with Scanner we can read data
int a = in.nextInt(); //first variable
int b = in.nextInt(); //second variable
int max; // to store maximum value from a or b
//Let's find maximum value
if (a >= b) {
max = a;
} else {
max = b;
}
int count = 0; // We count divisible number
for (int i=2; i<=max; i++) { // we start from 2, because we can't divide on 0, and every number divisible on 1
if (a % i == 0 && b % i==0) {
count++; //count them
}
}
if (count == 0) { // if there is no divisible numbers
System.out.println("Prime"); // that's our solutions
} else {
System.out.println("Not Prime"); //otherwise
}
}
}
I think that, this is the simple solution. Ask questions in comments.
I just gave a coding interview on codility
I was asked the to implement the following, but i was not able to finish it in 20 minutes, now I am here to get ideas form this community
Write a function public int whole_cubes_count ( int A,int B ) where it should return whole cubes within the range
For example if A=8 and B=65, all the possible cubes in the range are 2^3 =8 , 3^3 =27 and 4^3=64, so the function should return count 3
I was not able to figure out how to identify a number as whole cube. How do I solve this problem?
A and B can have range from [-20000 to 20000]
This is what I tried
import java.util.Scanner;
class Solution1 {
public int whole_cubes_count ( int A,int B ) {
int count =0;
while(A<=B)
{
double v = Math.pow(A, 1 / 3); // << What goes here?
System.out.println(v);
if (v<=B)
{
count=count+1;
}
A =A +1;
}
return count ;
}
public static void main(String[] args)
{
System.out.println("Enter 1st Number");
Scanner scan = new Scanner(System.in);
int s1 = scan.nextInt();
System.out.println("Enter 2nd Number");
//Scanner scan = new Scanner(System.in);
int s2 = scan.nextInt();
Solution1 n = new Solution1();
System.out.println(n.whole_cubes_count (s1,s2));
}
}
Down and dirty, that's what I say.
If you only have 20 minutes, then they shouldn't expect super-optimized code. So don't even try. Play to the constraints of the system which say only +20,000 to -20,000 as the range. You know the cube values have to be within 27, since 27 * 27 * 27 = 19683.
public int whole_cubes_count(int a, int b) {
int count = 0;
int cube;
for (int x = -27; x <= 27; x++) {
cube = x * x * x;
if ((cube >= a) && (cube <= b))
count++;
}
return count;
}
For the positive cubes:
i = 1
while i^3 < max
++i
Similarly for the negative cubes but with an absolute value in the comparison.
To make this more general, you need to find the value of i where i^3 >= min, in the case that both min and max are positive. A similar solution works if both min and max are negative.
Well, it can be computed with O(1) complexity, we will need to find the largest cube that fits into the range, and the smallest one. All those that are between will obviously also be inside.
def n_cubes(A, B):
a_cr = int(math.ceil(cube_root(A)))
b_cr = int(math.floor(cube_root(B)))
if b_cr >= a_cr:
return b_cr - a_cr + 1
return 0
just make sure your cube_root returns integers for actual cubes. Complete solution as gist https://gist.github.com/tymofij/9035744
int countNoOfCubes(int a, int b) {
int count = 0;
for (int startsCube = (int) Math.ceil(Math.cbrt(a)); Math.pow(
startsCube, 3.0) <= b; startsCube++) {
count++;
}
return count;
}
The solution suggested by #Tim is faster than the one provided by #Erick, especially when A...B range increased.
Let me quote the ground from github here:
"one can notice that x³ > y³ for any x > y. (that is called monotonic function)
therefore for any x that lies in ∛A ≤ x ≤ ∛B, cube would fit: A ≤ x³ ≤ B
So to get number of cubes which lie within A..B, you can simply count number of integers between ∛A and ∛B. And number of integers between two numbers is their difference."
It seems perfectly correct, isn't it? It works for any power, not only for cube.
Here is my port of cube_root method for java:
/*
* make sure your cube_root returns integers for actual cubes
*/
static double cubeRoot(int x) {
//negative number cannot be raised to a fractional power
double res = Math.copySign(Math.pow(Math.abs(x), (1.0d/3)) , x);
long rounded_res = symmetricRound(res);
if (rounded_res * rounded_res * rounded_res == x)
return rounded_res;
else
return res;
}
private static long symmetricRound( double d ) {
return d < 0 ? - Math.round( -d ) : Math.round( d );
}
I am aware of Math.cbrt in java but with Math.pow approach it is easy to generalize the solution for other exponents.
I am trying to create a program that will tell if a number given to it is a "Happy Number" or not. Finding a happy number requires each digit in the number to be squared, and the result of each digit's square to be added together.
In Python, you could use something like this:
SQUARE[d] for d in str(n)
But I can't find how to iterate through each digit in a number in Java. As you can tell, I am new to it, and can't find an answer in the Java docs.
You can use a modulo 10 operation to get the rightmost number and then divide the number by 10 to get the next number.
long addSquaresOfDigits(int number) {
long result = 0;
int tmp = 0;
while(number > 0) {
tmp = number % 10;
result += tmp * tmp;
number /= 10;
}
return result;
}
You could also put it in a string and turn that into a char array and iterate through it doing something like Math.pow(charArray[i] - '0', 2.0);
Assuming the number is an integer to begin with:
int num = 56;
String strNum = "" + num;
int strLength = strNum.length();
int sum = 0;
for (int i = 0; i < strLength; ++i) {
int digit = Integer.parseInt(strNum.charAt(i));
sum += (digit * digit);
}
I wondered which method would be quickest to split up a positive number into its digits in Java, String vs modulo
public static ArrayList<Integer> splitViaString(long number) {
ArrayList<Integer> result = new ArrayList<>();
String s = Long.toString(number);
for (int i = 0; i < s.length(); i++) {
result.add(s.charAt(i) - '0');
}
return result; // MSD at start of list
}
vs
public static ArrayList<Integer> splitViaModulo(long number) {
ArrayList<Integer> result = new ArrayList<>();
while (number > 0) {
int digit = (int) (number % 10);
result.add(digit);
number /= 10;
}
return result; // LSD at start of list
}
Testing each method by passing Long.MAX_VALUE 10,000,000 times, the string version took 2.090 seconds and the modulo version 2.334 seconds. (Oracle Java 8 on 64bit Ubuntu running in Eclipse Neon)
So not a lot in it really, but I was a bit surprised that String was faster
In the above example we can use:
int digit = Character.getNumericValue(strNum.charAt(i));
instead of
int digit = Integer.parseInt(strNum.charAt(i));
You can turn the integer into a string and iterate through each char in the string. As you do that turn that char into an integer
This code returns the first number (after 1) that fits your description.
public static void main(String[] args) {
int i=2;
// starting the search at 2, since 1 is also a happy number
while(true) {
int sum=0;
for(char ch:(i+"").toCharArray()) { // casting to string and looping through the characters.
int j=Character.getNumericValue(ch);
// getting the numeric value of the current char.
sum+=Math.pow(j, j);
// adding the current digit raised to the power of itself to the sum.
}
if(sum==i) {
// if the sum is equal to the initial number
// we have found a number that fits and exit.
System.out.println("found: "+i);
break;
}
// otherwise we keep on searching
i++;
}
}