int value = 1234;
char[] chars = String.valueOf(value).toCharArray();
How would I display those value as integers?
Almost there. You are missing an important piece though. You need to call sort() on Arrays
public static void main(String[] args) {
int value = 1234;
char[] arr = String.valueOf(value).toCharArray();
Arrays.sort(arr);
System.out.println(arr[0] + " " + arr[arr.length - 1]);
}
O/P :
1 4 // arr[0] is min and arr[arr.length-1] is max
You can do this using for loop ,only if you want to display these numbers seperately.I suggest you want to display all four digits in seperate four lines.it will be done by bellow code.
int value = 1234;
char [] chars = String.valueOf(value).toCharArray();
for(int i=0; i < chars.length ; i++ )
System.out.println(chars[i]);
public static void main(String[] args) {
int value = 1234;
List<Integer> output = new ArrayList<Integer>();
while (value > 0) {
output.add(value % 10);
value /= 10;
}
Collections.sort(output);
System.out.println("Min:" + output.get(0));
System.out.println("Max:" + output.get(output.size() - 1));
}
You will need a loop to pull of each individual digit and compare it to the current min/max :
int n = 36348;
int min = Integer.MAX_VALUE;
int max = Integer.MIN_VALUE;
if (n > 0) {
while (n > 0) {
int digit = n % 10;
max = Math.max(max, digit);
min = Math.min(min, digit);
n /= 10;
}
}
System.out.println(min);
System.out.println(max);
Related
num = Integer.parseInt(tf1.getText());
entered = Integer.parseInt(tf1.getText());
num2 = Integer.parseInt(tf2.getText());
entered2 = Integer.parseInt(tf2.getText());
for (i =(int) num; i<= num2 ; i++){
for (j=0 ; j >= i ; j++) {}
System.out.println(i);
}
do i have to use array list ? ArrayList<Integer> lists = new ArrayList<Integer>();
and if i use it how i can to separate each number in the arraylist,so I found the numbers between two numbers but how I can take each number and do the collatz conjecture java , please i need help quickly
The collatz conjecture is simple n = n/2 if n%2 == 0 and n = 3*n + 1 if n%2 == 1 and you're doing these calculations until n = 1. Based on this, you could write your function like this:
public static List<Integer> calculateConjecture(int number) {
List<Integer> values = new ArrayList<>();
while (number != 1) {
if (number % 2 == 0) {
number = number / 2;
} else {
number = 3 * number + 1;
}
values.add(number);
}
return values;
}
public static void main(String[] args) {
int inferiorLimit = 11;
int superiorLimit = 15;
for (int i = inferiorLimit; i <= superiorLimit; i++) {
System.out.println(calculateConjecture(i));
}
}
The values ArrayList will hold the sequence of numbers for the current number between the [inferiorLimit,superiorLimit]
I have to write a function that multiplies two numbers represented by two int arrays (so I can't use ArrayLists or something).
Each digit of a number is represented by an int between 0 and 9 in the array, no element should be greater than that.
The first element of the array represents the last digit of the number and so on, therefore the number 1234 would be {4,3,2,1} as an array in this function.
I thought multiplying those arrays that way would be similar to long multiplication, so I tried to implement it in a similar way: You multiply every digit of the first array with every digit of the second one and store the rest if the result is equal or greater to 10 and then add it to the next digit. However, I seem to have done something wrong in the code (maybe the calculation of the rest??) because the result of my function is not correct: I tested it with 190 times 86 (represented by the arrays {0,9,1} and {6,8}) and get 15342 ({2,4,3,5,1}) instead of the actual result 16340 (which would be {0,4,3,6,1}).
Can somebody here help me out with this please? This is my code:
import java.util.Arrays;
public class MultiplyArrays {
static int[ ] times(int[ ] a, int[ ] b) {
int[] arr = new int[a.length + b.length - 1];//arr should be the result of a*b. The result shouldn't be shorter than that
int tmp = 0;//stores the rest of two-digit numbers
for(int i = b.length - 1; i >= 0; i--){
for(int j = 0; j < a.length; j++){//should multiply all digits of a with the current index of b
arr[i + j] = (arr[i + j] + (b[i] * a[j] + tmp)) % 10;//sets the value of the (i+j)th index in arr to the multiplication of two numbers from a and b adding the rest tmp.
if((arr[i + j] + b[i] * a[j] + tmp) < 10){//if this number is less than 10, there is no rest
tmp = 0;
}
else{//otherwise, the rest should be the second digit
tmp = (((arr[i + j] + (b[i] * a[j] + tmp))) - ((arr[i + j] + (b[i] * a[j] + tmp)) % 10)) / 10;//something in the formula for the rest is wrong, I guess
}
}
}
if(tmp != 0){//if the last number of the array containing the result is calculated and there still is a rest, a new array with one more digit is created
int[] arr2 = new int[arr.length + 1];
for(int i = arr.length - 1; i >= 0; i--){//the new array copies all numbers from the old array
arr2[i] = arr[i];
arr2[arr2.length - 1] = tmp;//the last space is the rest now
}
return arr2;
}
else{//if there is no rest after calculating the last number of arr, a new array isn't needed
return arr;
}
}
public static void main(String[] args) {//test the function with 190 * 86
int[] a = {0,9,1};
int[] b = {6,8};
System.out.println(Arrays.toString(times(a,b)));
}
}
Maybe this comes from the fact that your indices in the for-loops of the times()-method are incrementing AND decrementing.
The i is going down and the j is going up.
Also, in the second for loop, you should only increment to 'a.length - 1', not to 'a.length'.
Arbitrary precision multiplication is more complex than it seems, and contains corner cases (like one and zero). Fortunately, Java has an arbitrary precision type; BigInteger. In order to use it here, you would need to create two additional methods; one for converting an int[] to a BigInteger, and the second the convert a BigInteger to an int[].
The first can be done with a single loop adding each digit at index i (multiplied by 10i) to a running total. Like,
private static BigInteger fromArray(int[] arr) {
BigInteger bi = BigInteger.ZERO;
for (int i = 0, pow = 1; i < arr.length; pow *= 10, i++) {
bi = bi.add(BigInteger.valueOf(arr[i] * pow));
}
return bi;
}
And the second can be done a number of ways, but the easiest is simply to convert the BigInteger to a String to get the length() - once you've done that, you know the length of the output array - and can populate the digits in it. Like,
private static int[] toArray(BigInteger bi) {
String s = bi.toString();
int len = s.length();
int[] r = new int[len];
for (int i = 0; i < len; i++) {
r[i] = s.charAt(len - i - 1) - '0';
}
return r;
}
Finally, call those two methods and let BigInteger perform the multiplication. Like,
static int[] times(int[] a, int[] b) {
BigInteger ba = fromArray(a), bb = fromArray(b);
return toArray(ba.multiply(bb));
}
Running your original main with those changes outputs (as expected)
[0, 4, 3, 6, 1]
Well, your thought would work with addition, but on multiplication you multiply each digit of one with the whole number of the other and step one digit to the left (*10) each time you change the multiplication digit of the first number.
So you might brought something into confusion.
I just solved it in a more structured way, running the debugger will hopefully explain the process. In the solutions you can remove the trailing / leading zero by checking the digit if 0 and replace the array with one of length - 1.
The solutions are:
With conditions mentioned (numbers in reverse order):
public static void main(String[] args) {
int[] a = {3,2,1};
int[] b = {9,8};
System.out.println("Result is: " + Arrays.toString(calculate(a, b)));
}
private static int[] calculate(int[] a, int[] b) {
// final result will be never longer than sum of number lengths + 1
int[] finalResult = new int[a.length + b.length + 1];
int position = 0;
for(int i = 0; i < a.length; i++) {
int[] tempResult = multiplyWithOther(a[i], b);
addToFinalResult(finalResult, tempResult, position);
position++;
}
return finalResult;
}
private static int[] multiplyWithOther(int number, int[] otherArray) {
// The number cannot be more digits than otherArray.length + 1, so create a temp array with size +1
int[] temp = new int[otherArray.length + 1];
// Iterate through the seconds array and multiply with current number from first
int remainder = 0;
for(int i = 0; i < otherArray.length; i++) {
int result = number * otherArray[i];
result += remainder;
remainder = result / 10;
temp[i] = result % 10;
}
// Add remainder (even if 0) to start
temp[temp.length - 1] = remainder;
return temp;
}
private static void addToFinalResult(int[] finalResult, int[] tempResult, int position) {
int remainder = 0;
for(int i = 0; i < tempResult.length; i++) {
int currentValue = tempResult[i];
int storedValue = finalResult[i + position];
int sum = storedValue + currentValue + remainder;
remainder = sum / 10;
finalResult[i + position] = sum % 10;
}
finalResult[position + tempResult.length] = remainder;
}
And with numbers in normal order in array:
public static void main(String[] args) {
int[] a = {1,2,3,6};
int[] b = {8, 9, 1};
System.out.println("Result is: " + Arrays.toString(calculate(a, b)));
}
private static int[] calculate(int[] a, int[] b) {
// final result will be never longer than sum of number lengths + 1
int[] finalResult = new int[a.length + b.length + 1];
int positionFromEnd = 0;
for(int i = 1; i <= a.length; i++) {
int[] tempResult = multiplyWithOther(a[a.length-i], b);
addToFinalResult(finalResult, tempResult, positionFromEnd);
positionFromEnd++;
}
return finalResult;
}
private static int[] multiplyWithOther(int number, int[] otherArray) {
// The number cannot be more digits than otherArray.length + 1, so create a temp array with size +1
int[] temp = new int[otherArray.length + 1];
// Iterate through the seconds array and multiply with current number from first
int remainder = 0;
for(int i = 1; i <= otherArray.length; i++) {
int result = number * otherArray[otherArray.length - i];
result += remainder;
remainder = result / 10;
temp[otherArray.length - i +1] = result % 10;
}
// Add remainder (even if 0) to start
temp[0] = remainder;
return temp;
}
private static void addToFinalResult(int[] finalResult, int[] tempResult, int positionFromEnd) {
int remainder = 0;
for(int i = 1; i <= tempResult.length; i++) {
int currentValue = tempResult[tempResult.length - i];
int storedValue = finalResult[finalResult.length - positionFromEnd - i];
int sum = storedValue + currentValue + remainder;
remainder = sum / 10;
finalResult[finalResult.length - positionFromEnd - i] = sum % 10;
}
finalResult[finalResult.length - positionFromEnd - tempResult.length - 1] = remainder;
}
I have a program that is supposed to decrypt a number to its primes. The primes also have an order: for instance, 2 is the 1st prime number, 3 is the second 5 is the third and so on. The indexes are 1 is for a, two is for b, three is for c and so on. I don't know how to compare the two array lists in order to assign an index to each prime so I can decode a word which is encrypted in the number 72216017. The number 72216017 has the primes 17,19,47,67,71. If 2,3,5,7,11... are a,b,c,d,e... these five prime numbers make up the word ghost, I just don't know how to assign and sort these numbers by their index.
package name;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class PrimeFactorsEffective {
private static int z;
private int w = z;
public static List<Integer> primeFactors(int numbers) {
int n = numbers;
List<Integer> factors = new ArrayList<Integer>();
for (int i = 2; i <= n / i; i++) {
while (n % i == 0) {
factors.add(i);
n /= i;
}
if (n > 1) {
factors.add(n);
System.out.println(factors);
z = Collections.max(factors);
}
}
return factors;
}
public static void main(String[] args) {
System.out.println("Primefactors of 72216017");
for (Integer integer : primeFactors(72216017)) {
System.out.println(integer);
}
List<Integer> factors1 = new ArrayList<Integer>();
List<String> index1 = new ArrayList<String>();
int i;
int element = 0;
int num = 0;
int maxCheck = z; // maxCheck limit till which you want to find prime numbers
boolean isPrime = true;
String primeNumbersFound = "";
//Start loop 1 to maxCheck
for (i = 1; i <= maxCheck; i++) {
isPrime = CheckPrime(i);
if (isPrime) {
primeNumbersFound = primeNumbersFound + i + " ";
factors1.add(i);
factors1.get(num);
}
}
System.out.println("Prime numbers from 1 to " + maxCheck + " are:");
System.out.println(factors1);
}
public static boolean CheckPrime(int numberToCheck) {
int remainder;
for (int i = 2; i <= numberToCheck / 2; i++) {
remainder = numberToCheck % i;
if (remainder == 0) {
return false;
}
}
return true;
}
}
You can store the primes in a List (primes in this list will be in increasing order). Now you can use Collections.BinarySearch to get the index of the prime for which you wan to find the corresponding alphabet. Once you got the index (index here according to you starts from 1, so a's index is 1, b's index is 2, c's index is 3 and so on) you can do simply something like char currentCharacter = (char) ('a' + primeIndex - 1) and the variable currentCharacter will store the alphabet corresponding to primeIndex.
Some other minor things that I'd like to suggest:
Which checking whether a number is prime or not, you can simply check upto square-root of numberToCheck. So you can replace your loop for (int i = 2; i <= numberToCheck / 2; i++) to for (int i = 2; i*i <= numberToCheck; i++). Note that It is not a good idea to calculate square-root using Math.sqrt, instead you can have a condition like i*i <= numberToCheck.
Please refrain from naming your packages that seem to be random.
As of Java SE 7 explicit type-arguments while initializing the list are not required. You can replace List<Integer> factors1 = new ArrayList<Integer>() with List<Integer> factors1 = new ArrayList<>(). Please read this for more information.
Your factor method don't really look good to me, it don't give correct results. Please see the following method that gives correct result:
{{
public static List<Integer> primeFactors(int numbers) {
int n = numbers;
List<Integer> factors = new ArrayList<>();
for (int i = 2; n>1; i++) {
while (n % i == 0) {
factors.add(i);
n /= i;
}
}
z = Collections.max(factors);
return factors;
}
I have an int that ranges from 0-99. I need to get two separate ints, each containing one of the digits. I can't figure out how to get the second digit. (from 64 how to get the 6) This is my code:
public int getNumber(int pos, boolean index){//if index = 1 - first digit, if index = 0 - second digit
int n;
if(index){
n = pos%10;
}else{
if(pos<10){
n=0;
}else{
//????
}
}
return n;
}
You can do integer division by 10. For example, in the following code res should equal 4:
int res = 42 / 10;
Simply divide by 10.
...
if(index) {
n = pos/10;
}
...
Simple: in order to get any leading digit; just create a loop; and during each run, divide by 10.
In your case, you can even omit the loop ;-)
you can do:
if(index){
return x % 10;
}
return x / 10;
or maybe a little something
public int getNumber(....){
return index ? x % 10 : x / 10;
}
Just divide the number by 10. If it's int, the result will be int.
class Main {
public static void main(String[] args) {
int a = 8;
int b = 28;
int c = 99;
System.out.println(a / 10);
System.out.println(b / 10);
System.out.println(c / 10);
}
}
Here is a trick. Replace your //???? with below code.
Integer posInt= new Integer(pos);
n=Integer.parseInt( posInt.toString().substring(0, 1));
Complete code should look like,
public int getNumber(int pos, boolean index){//if index = 1 - first digit, if index = 0 - second digit
int n;
if(index){
n = pos%10;
}else{
if(pos<10){
n=0;
}else{
Integer posInt= new Integer(pos);
n=Integer.parseInt( posInt.toString().substring(0, 1));
}
}
return n;
}
Scanner scan = new Scanner(System.in);
System.out.println("Give a number");
int n = scan.nextInt();
int secondNumber = 0;
while (n > 9) {
secondNumber= n % 10;
n /= 10;
}
to find the first number you need to add to while a constant = n/10; (firstNumber = n / 10;)
import java.util.Scanner;
import java.util.Arrays;
class Solve
{
public static void main(String args[])
{
Scanner in = new Scanner(System.in);
int i=0,count=0;
int[] arr = new int[10];
int n =in.nextInt();
while(n!=0)
{
arr[i]=n%2;
i++;
n=n/2;
}
System.out.println(Arrays.toString(arr));
}
}
}
I just want to calculate number of consecutive 1's. ? like 1110011001 will give me answer 5.. How can i do that??
System.out.println(Integer.toBinaryString(n).replaceAll("(0|(?<!1)1(?!1))", "").length());
The regex means: replace all 0's and any 1 not preceded or followed by another 1
You can handle this as a String [Edited to sum all consecutive 1's]:
String binary = in.nextLine();
String[] arrayBin = binary.split("0+"); // an array of strings without 0's
int result=0;
for (int i=0; i < arrayBin.length; i++){
if (arrayBin[i].length()<2){
result+=0;
}
else {
result+=arrayBin[i].length();
}
}
System.out.println("Total consecutive = "+result);
We can identify two consecutive binary ones in the least significant positions like this:
(value & 0b11) == 0b11
We can move the bits in value to the right like so:
value >>>= 1;
It's important to use tripple >>> over double >> because we don't care about the sign bit.
Then all we have to do is keep track of the number of consecutive 1s:
int count(int value) {
int count = 1;
int total = 0;
while (value != 0) {
if ((value & 0b11) == 0b11) {
count++;
} else {
if (count > 1) {
total += count;
}
count = 1;
}
value >>>= 1;
}
return total;
}
Test cases:
assertEquals(0, count(0b0));
assertEquals(0, count(0b1));
assertEquals(0, count(0b10));
assertEquals(2, count(0b11));
assertEquals(5, count(0b1110011));
assertEquals(5, count(0b1100111));
assertEquals(6, count(0b1110111));
assertEquals(7, count(0b1111111));
assertEquals(32, count(-1));
If you only want the length of the maximum, I have a similar answer: https://stackoverflow.com/a/42609478/360211
You can make use of Brian Kernighan’s Algorithm for counting the highest consecutive number of 1's.
A java pseudocode would be something like this
// Initialize result
int count = 0;
// Count the number of iterations to
// reach n = 0.
while (n!=0)
{
// This operation reduces length
// of every sequence of 1s by one.
n = (n & (n << 1));
count++;
}
public class Solution {
public int findMaxConsecutiveOnes(int[] nums) {
if(nums == null || nums.length == 0){
return 0;
}
int counter = 0, max = Integer.MIN_VALUE;
for(int i = 0; i < nums.length; i++){
if(nums[i] == 1){
counter += nums[i];
} else{
counter = nums[i];
}
max = Math.max(counter, max);
}
return max;
}
}
To this problem one trick which we can use here with help of some Java operators.
& operator and left shift (<<) in java.
Code snippet will be like :
public getConsecutiveCount(int inputNumber)
{
int count = 0 ;
while(inputNumber != 0)
{
inputNumber = inputNumber & (inputNumber << 1);
count++;
}
}
Explanation :
This function is taking input (ex : we want to check how many
consecutive 1's integer 6 have in its binary representation)
so out input number will be like :
inputNumber = ((110) & ((110)<<1)) {This left shift will result in 100 so final op :
110 & 100 which 100 , every time '0' is added to
our result and we iterate until whole number will
be zero and value of our count variable will be
our expected outcome }
To find Maximum consecutive 1's in binary(like 101)
int n = Convert.ToInt32(Console.ReadLine());
string[] base2=Convert.ToString(n,2).Split('0');
int count=0;
foreach(string s in base2)
count=s.Length>count?s.Length:count;
Console.WriteLine(count);
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
String bs = Integer.toBinaryString(n);// bs=Binary String
char[] characters = bs.toCharArray();
int max = 1;
int temp = 1;
for (int i = 0; i < characters.length - 1; i++) {
if (characters[i] == characters[i + 1] & characters[i] == '1' & characters[i + 1] == '1') {
temp++;
if (temp > max) {
max = temp;
}
} else {
temp = 1;
}
}
System.out.println(max);
}
/* Given a decimal number print maximum number of consecutive 1's after binary conversion */
import java.io.*;
import java.util.*;
public class Solution {
public void countBinaryOne(int num){
int var =0, countOne= 0, maxCt=0;
while(num>0){
var= num%2;
if(var==1){
countOne=countOne+1;
}else{
if(maxCt<countOne){
maxCt= countOne;
countOne=0;
}else{
countOne=0;
}
}
num=num/2;
}
System.out.println(Math.max(countOne,maxCt));
}
public static void main(String[] args) {
Scanner in= new Scanner(System.in);
int n= in.nextInt();
Solution sol= new Solution();
sol.countBinaryOne(n);
}
}
public static void digitBinaryCountIfOne(int n){
int reminder=0, sum=0, total = 0;
while(n>0)
{
reminder = n%2;
n/=2;
if(reminder==1){
sum++;
if(sum>=total)
total=sum;
}else{
sum=0;
}
}
System.out.println(total);
}