public class Nodigeven {
static int even=0;
static int count=0;
static int findnodigeven(int[] arr) {
for(int i=0;i<arr.length;i++) {
while(arr[i]!=0) {
arr[i]= arr[i]/10;
count++;
}
if(count%2==0) {
even++;
}
}
return even;
}
public static void main(String[] args) {
int[] arr = {122,255,133,14,15,16};
System.out.println(findnodigeven(arr));
}
}
am getting wrong output i.e : 1 .. can you tell me where i am going wrong here in the code
As far as I can tell you have two errors. The first is that you did not reset count to 0 for each iteration of the loop. The second is that you did not check the special case of 0 in the array. 0 is a single digit and thus odd. But since you never enter the while loop, count will remain 0 and even will be incremented.
public class Nodigeven {
static int findnodigeven(int[] arr) {
for (int i = 0; i < arr.length; i++) {
int count = 0;
// check for 0 value and skip.
if (arr[i] == 0) {
continue;
}
while (arr[i] != 0) {
arr[i] = arr[i] / 10;
count++;
}
if (count % 2 == 0) {
even++;
}
}
return even;
}
public static void main(String[] args) {
int[] arr = { 122, 255,0, 133, 14, 15, 16 };
System.out.println(findnodigeven(arr));
}
}
If you're interested you and do this without explicitly counting the digits. Use Math.log10() to get the count, again skipping 0 since the log of 0 is undefined. The number of digits in a decimal number N is Math.log10(N)+1. You can use the conditional operator to add 1 or 0 as appropriate to the parity count.
public class Nodigeven {
static int even = 0;
static int findnodigeven(int[] arr) {
int even = 0;
for (int i = 0; i < arr.length; i++) {
even += arr[i] != 0 &&
(int) (Math.log10(arr[i])+1) % 2 == 0
? 1 : 0;
}
return even;
}
public static void main(String[] args) {
int[] arr = { 122, 255,0, 133, 14, 15, 16 };
System.out.println(findnodigeven(arr));
}
}
Related
I am stuck on an issue that I cannot seem to resolve. I cannot seem to to test my code correctly. My code is as follows
public static int sum13( int[] nums) {
int sum = 0;
for(int i = 0; i <= nums.length - 1; i++){
if( nums[i] != 13){
sum += nums[i];
if(i > 0 && nums[i-1] == 13)
sum -= nums[i];
}
}
return sum;
}
public static void main(String[] args) {
}
If I try to put System.out.println(sum13([1,2,2,1]) I am met with several errors relating to the [] as well as the ,. I cannot figure out, what it is that I've done wrong.
Return the sum of the numbers in the array, returning 0 for an empty array. Except the number 13 is very unlucky, so it does not count and numbers that come immediately after a 13, also do not count. sum13([1, 2, 2, 1]) →6
sum13([1, 1]) →2
I decided to add flag to know when the previous value was 13. In that way, you don't have to deal with edge cases.
public static int sum13(int[] nums) {
int sum = 0;
boolean was13 = false;
for(int i = 0; i < nums.length; i++) {
if(nums[i] == 13) {
was13 = true;
} else {
if(!was13)
sum += nums[i];
was13 = false;
}
}
return sum;
}
A possible solution with some test cases:
public static int sum13(int[] numbers)
{
int sum = 0;
int prev = 0;
for (var number : numbers)
{
if (number != 13 && prev != 13)
{
sum += number;
}
prev = number;
}
return sum;
}
public static void main(String[] args)
{
System.out.println(sum13(new int[]{}));
System.out.println(sum13(new int[]{1, 2, 3, 4, 5}));
System.out.println(sum13(new int[]{13, 1, 13, 13, 2, 3, 4, 5}));
}
I am very new to Java and I am trying to iterate over an array of integers and get all multiples of 10. What I get with my code is the elements in the array printed 100 times since that is the length of the array. I know it is very basic but I just can't figure the problem out. This is what I have:
import java.util.Arrays;
public class ArrayThings {
public static void main(String[] args) {
int[] myFirstArray = new int[100];
for (int i = 0; i < myFirstArray.length; i++) {
myFirstArray[i] = i;
}
for (int i : myFirstArray) {
if (i % 10 == 0) {
myFirstArray[i] = i;
} else {
i++;
}
System.out.println(Arrays.toString(myFirstArray));
}
}
}
I think that is what you want to do :
public class ArrayThings {
public static void main(String[] args) {
int[] myFirstArray = new int[100];
// array generation
for (int i = 0; i < myFirstArray.length; i++) {
myFirstArray[i] = i;
}
// printing multiples of 10
for (int i = 0; i < myFirstArray.length; i++) {
if (i % 10 == 0 && i != 0) {
System.out.println(myFirstArray[i]);
}
}
}
}
In Java-8 you can do it like below:
int result[] = IntStream.range(1, 100).filter(e -> e%10==0).toArray();
System.out.println(Arrays.toString(result));
Why do you need an array for printing multiples of 10? You could simply do:
public class ArrayThings{
public static void main(String[]args){
for(int i=0; i<101; i++) {
if(i%10==0 && i != 0){
System.out.println(i);
}
}
}}
P.S. you are printing whole array and not that particular element, that's why you are getting a wrong output.
You should move your print statement outside of the for loop, that is what is causing it to print 100 times.
Also your current code seems to do absolutely nothing. You are checking the modulo of i, then setting the value of myFirstArray to that value of i. The current value of myFirstArray at i, is already equal to i, as initialized in the first loop.
This should work
import java.util.Arrays;
public class ArrayThings {
public static void main(String[] args) {
int[] myFirstArray = new int[100];
int[] myMultiplesArray = new int[9];
for (int i = 0; i < myFirstArray.length; i++) {
myFirstArray[i] = i;
}
int j = 0;
for (int i : myFirstArray) {
if (i % 10 == 0) {
myMultiplesArray[j] = i;
j++;
}
}
System.out.println(Arrays.toString(myMultiplesArray));
}
}
I am trying to print 122333221 using recursion if n is 3.But i am not able to solve it.We have given the number we have to print the series using recursion.For example if n = 3 then it should print 122333221.
public static void print(int n){
if(n < 1 ){
return;
}
print(n-1);
for(int i = 1; i <= n; i++){
System.out.print(n);
}
}
public static void main(String[] args) {
print(3);
}
You have to use the normal technique of keeping track of your state through parameters by defining a public method which uses a private method with extra parameters.
// Repeats n n times.
private static void repeat(int n) {
for (int i = 0; i < n; i++) {
System.out.print(n);
}
}
private static void print(int n, int v) {
if (n == v) {
// Just once for the deepest level.
repeat(n);
} else {
// Wrap the inner print ...
repeat(n);
// Recurse with the next higher value.
print(n + 1, v);
// ... end the wrap.
repeat(n);
}
}
public static void print(int n) {
System.out.print(n+": ");
print(1, n);
System.out.println();
}
public void test(String[] args) {
for (int i = 1; i <= 9 ; i++) {
print(i);
}
}
a possible solution will be n is the number of the different digits you have , while you need to print each digit times its value, so if n = 1
result =1
n =2 result 1221
n = 3, result 122333221
n = 4, result 1223334444333221
The implemenation is not hard , the base case is the number = n and its printed n times and you always print recursivly unless you reached n, the first call is always
solve(n, 1,1);
The implementation:
public void solve(int n, int numberOfPrints, int num) {
if(numberOfPrints == 0 && n ==num )
return ;
if(numberOfPrints == 0 )
solve(n, num+1,num+1);
System.out.print(num);
solve(n, numberOfPrints-1, num);
if(num == n)
return;
System.out.print(num);
}
public static void PrintSeries(int seriesNum, int currentNum, bool movingForward)
{
if(movingForward && currentNum < seriesNum)
{
PrintNum(currentNum);
PrintSeries(seriesNum, currentNum + 1, true);
}
else if(movingForward && currentNum == seriesNum)
{
PrintNum(currentNum);
PrintSeries(seriesNum, currentNum - 1, false);
}
else
{
if(currentNum > 0)
{
PrintNum(currentNum);
}
if(currentNum - 1 > 0)
{
PrintSeries(seriesNum, currentNum - 1, false);
}
}
}
public static void PrintNum(int num)
{
for(int x = 0; x < num; x++)
{
System.out.print(num);
}
}
Recently i attended one interview there they asked me to write a program like below,
A number chain is created by continously adding the square of the digits in a number
to form a new number untill its has been seen before.
example :
44 -> 32 -> 13-> 10-> 1
85->89->145->42->20->4->16->37->58->89
therefore any chain arrives at 1 or 89 will become stuck in endless loop.
what is most amazing is that every starting number will eventually arrive at 1 or 89.
write a program to count the starting number below 10000 will arrive at 89?
I wrote programs like below,
int num =44;
int array[] = new int[100];
int power=0;
while(num > 0)
{
int mod = num % 10;
int div = num /10;
int sum =(mod * mod) + (div * div);
num =sum;
System.out.print(" => "+sum);
if(array.equals(sum))
// should not use any functions like Arrays.asList(array).contains(sum);
return;
else
{
//System.out.println("else");
array[power++] =sum;
}
}
I know that above program not satisfy their requirements.Some one tell me good code snip to make them code satisfaction(If same question ask in future).?
Note : should not use any function or import. Only logic is need.
Maintain a cache of already calculated numbers. This will reduce the number of unnecessary iterations which were already calculated.
Let's do some math
From you example
44 -> 32 -> 13-> 10-> 1
85->89->145->42->20->4->16->37->58->89
You already know that the numbers 85, 89, 145, 42, 20, 4, 16, 37, 58 lead to 89 and 44, 32,13, 10, 1 don't.
In some case say calculating it for 11.
11 - 2 - 4
Now we already know 4 leads to 89 and so we skip all the other unnecessary iteration from
4 - 16 - 37 - 58 - 89 and also we now know that 11, 2also lead to 89.
So no the algorithm would be:
while(num > 0)
{
if(calculate[i] == 1)//which mean leads to 89
{
// dont calculate again
}
else
{
// num = // your squares logic
}
}
I read this as a recursive problem. I made the assumption that you only want to know the number of steps until 1 or 89 is reached.
The helper method, getDigits() is just for simplicity. The conversion to the String isn't technically necessary, but it makes the code simple.
public static void main(String[] args) {
int v = 9843;
int[] count = {0};
System.out.println("Number of steps: " + countSteps(v,count)[0]);
}
private static int[] countSteps(int initialValue, int[] count){
if(initialValue == 1 || initialValue == 89){
return count;
}
count[0]++;
int[] digits = getDigits(initialValue);
initialValue = 0;
for (int k : digits) {
initialValue += k * k;
}
countSteps(initialValue,count);
return count;
}
private static int[] getDigits(int i){
String s = Integer.toString(i);
int[] digits = new int[s.length()];
for(int j=0;j<s.length();j++){
digits[j] = s.charAt(j) - '0';
}
return digits;
}
If you are generating a sequence it makes sense to use an Iterable.
public static class SquaredDigitsSequence implements Iterable<Integer> {
int start;
SquaredDigitsSequence(int start) {
this.start = start;
}
#Override
public Iterator<Integer> iterator() {
return new SquaredDigitsIterator(start);
}
static class SquaredDigitsIterator implements Iterator<Integer> {
int last;
Set<Integer> seen = new HashSet<>();
SquaredDigitsIterator(int start) {
last = start;
seen.add(last);
}
#Override
public boolean hasNext() {
return !seen.contains(step());
}
#Override
public Integer next() {
last = step();
seen.add(last);
return last;
}
int step() {
int next = 0;
for (int x = last; x != 0; x /= 10) {
next += (x % 10) * (x % 10);
}
return next;
}
}
}
public void test() {
for (int i = 0; i < 100; i++) {
System.out.print(i + " ");
for (int x : new SquaredDigitsSequence(i)) {
System.out.print(x + " ");
}
System.out.println();
}
}
This prints all sequences up to 100 and does indeed include the two examples you posted but sadly it does not always terminate at 1 or 89.
class SquareDigits{
public static void main(String[] args){
System.out.println("Amount of numbers ending on 89: " + loop(10000));
}
public static int loop(int limit){
int cnt = 0;
for(int i = 1; i < limit; i++){
if(arriveAt89(i))
cnt++;
}
return cnt;
}
public static boolean arriveAt89(int num){
while(num != 89 && num != 1){
num = addSquares(num);
}
if(num == 89)
return true;
return false;
}
public static int addSquares(int n){
int sum = 0;
for(Character c : ("" + n).toCharArray()){
sum += Character.getNumericValue(c)*Character.getNumericValue(c);
}
return sum;
}
}
Assuming you're just after the amount of numbers that ends with 89.
This prints all numbers that end up in 89 below 89.
//array = boolean array to hold cache
//arr= list to store numbers in the chain that goes up to 89 used in setting cache
public static void main(String args[]) {
Boolean[] array = new Boolean[100];
Arrays.fill(array, Boolean.FALSE);
for(int i=2;i<89;i++){
checkChain(i,array);
}
for(int k=0;k<89;k++){
if(array[k]){System.out.println(k);}
}
}
private static void checkChain(int num,Boolean[] array) {
List<Integer> arr= new ArrayList<Integer>();
int initial = num;
int next;
do{
next=0;
arr.add(num);
while(num>0){
if(array[num] || num==89){
for(Integer j:arr){
array[j]=true;
}
break;
}
next = next+(num%10)*(num%10);
num=num/10;
}
num=next;
if(next<initial && array[next]){
array[initial]=true;
break;
}
}while((next>initial));
}
}
I have an assignment due for class and the objective is to take an Array and run it through a method that will print the array out in reverse order, then run it through a second method to test if the number is prime then print the still reversed order array out without the prime numbers. I can get the reverse the order part fine, I am running into trouble with the prime numbers part:
public class Driver {
public static void main(String[] args) {
// CTORs
int[] MyArray = { 10, 8, 7, 14, 22, 11 };
int[] myArray2 = new int[7];
// METHOD CALLING
MyArray = reverseOrder(6, MyArray);
MyArray = primeCheck(MyArray, 6);
for (int i = 0; i < myArray2.length; i++)
System.out.println(myArray2[i] + " ");
}// MAIN
/*--------------------ARRAY PRIME TEST---------------------*/
private static int[] primeCheck(int[] myArray, int num) {
//prime
boolean prime = true;
int[] myArray2 = new int[10];
//test all components of an array
for (int i = num + 1 ; i >= 0; i++) {
if (num % i > 0) {
prime = false;
System.arraycopy(myArray, 0, myArray2, 0, 4);
return myArray2;
}
}
return myArray2;
}// ISPRIME REMOVE
}// CLOSE CLASS
my output is as follows:
11 22 14 7 8 10 0
0
0
0
0
0
I feel really rusty because this is the first assignment back after a long break, so any guidance or help would be greatly appreciated.
myArray2 is defined and never filled with values. So every element is 0.
I think
for (int i = 0; i < myArray2.length; i++)
must be
for (int i = 0; i < myArray.length; i++)
There's definitely something wrong about for (int i = num + 1 ; i >= 0; i++). Below is one way to achieve the objective.
public static void main(String[] args) {
int[] arr = { 10, 8, 7, 14, 22, 11 };
for(int i = 0; i < arr.length; i++) {
if(!isPrime(arr[i])) {
System.out.print(arr[i] + " ");
}
}
}
public static boolean isPrime(int num) {
if(num < 2) return false;
if(num == 2) return true;
int remainder, divisor;
divisor = num - 1;
do {
try {
remainder = num % divisor;
} catch (ArithmeticException e) {
return false;
}
if(remainder == 0) return false;
divisor--;
} while (divisor > 1);
return true;
}