Other Java Problems
Other Java Problems
read the two array from the user and generate a third array containing all the
common elements from the first two.
in java
import java.util.*;
scanner.close();
}
}
------
import java.util.*;
scanner.close();
}
}
-----
reverse integer:
class Solution {
public int reverse(int x) {
int revN = 0;
while (x != 0) {
int digit = x % 10;
x /= 10;
if (revN > Integer.MAX_VALUE / 10 || (revN == Integer.MAX_VALUE / 10 &&
digit > 7)) return 0;
if (revN < Integer.MIN_VALUE / 10 || (revN == Integer.MIN_VALUE / 10 &&
digit < -8)) return 0;
revN = revN * 10 + digit;
}
return revN;
}
}
-----
Armstrong number:
import java.util.*;
public class Main{
static boolean ArmstrongNumber(int n)
{
int originalno = n;
int count = 0;
int temp = n;
while (temp != 0)
{
count++;
temp = temp / 10;
}
int sumofpower = 0;
while (n != 0)
{
int digit = n % 10;
sumofpower += Math.pow(digit,count);
n /= 10;
}
return (sumofpower == originalno);
}
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
int n1 = sc.nextInt();
if (ArmstrongNumber(n1))
{
System.out.println("true");
}
else
{
System.out.println("false");
}
}
}
--
print all divisors or sum of all divisors:
Problem statement
You are given an integer ‘n’.
Example:
Input: ‘n’ = 5
Output: 21
Explanation:
We need to find the sum of ‘sumOfDivisors(i)’ for all ‘i’ from 1 to 5.
‘sumOfDivisors(1)’ = 1
‘sumOfDivisors(2)’ = 2 + 1 = 3
‘sumOfDivisors(3)’ = 3 + 1 = 4
‘sumOfDivisors(4)’ = 4 + 2 +1 = 7
‘sumOfDivisors(5)’ = 5 + 1 = 6
Therefore our answer is sumOfDivisors(1) + sumOfDivisors(2) + sumOfDivisors(3) +
sumOfDivisors(4) + sumOfDivisors(5) = 1 + 3 + 4 + 7 + 6 = 21.
OR
----
Hashing:
import java.util.*;
class tUf {
int n;
n = sc.nextInt();
int[] arr = new int[n];
for (int i = 0; i < n; i++) {
arr[i] = sc.nextInt();
}
//precompute:
int[] hash = new int[13];
for (int i = 0; i < n; i++) {
hash[arr[i]] += 1;
}
int q;
q = sc.nextInt();
while (q-- != 0) {
int number;
number = sc.nextInt();
// fetching:
System.out.println(hash[number]);
}
}
}