Programming challenge

From XennisWiki
Jump to: navigation, search

In the most programming challenges you receive an integer or an array and have to compute a solution. This article provides some basic tips for Java.

Java tips

Integer

Get maximum values

// Maximum and minimum value of an integer
int int_max = Integer.MAX_VALUE;
int int_min = Integer.MIN_VALUE;

Add two big integers

// Wrong! Add big integers
int i = Integer.MAX_VALUE + Integer.MAX_VALUE; // -2, should be 4294967294
long j = Integer.MAX_VALUE + Integer.MAX_VALUE; // -2, should be 4294967294
// Right! Add big integers
long k = (long) Integer.MAX_VALUE + (long) Integer.MAX_VALUE; // 4294967294

Check integer is even or odd

int i = 5;
if ( (i % 2) == 0) {
    System.out.println("Integer is even");
} else {
    System.out.println("Integer is odd");
}

Calculate mean of two integers

int a = 50;
int b = 3;

// Wrong! Calculate mean of two integers
double mean = (a - b) / 2;
System.out.println(mean); // 23.0, should be 23.5
// Right! Calculate mean of two integers
double mean = (double) (a - b) / 2;
System.out.println(mean); // 23.5

Double

Round, ceil and floor a double

import java.lang.*;

double d = 23.4;
System.out.println((int) Math.round(mean)); // 23
System.out.println((int) Math.ceil(mean)); // 24
System.out.println((int) Math.floor(mean)); // 23

Array

Length of an array

int[] A = {-1, 3};
// Length of the array
int N = A.length;

Iterate over array

for(int i=0; i<N; i++) {
    System.out.println(A[i]);
}

Get minimum and maximum integer in an array

int A_min = Integer.MAX_VALUE;
int A_max = Integer.MIN_VALUE;
for(int i=0; i<N; i++) {
    if (A[i] < A_min) {
        A_min = A[i];
    }
    if (A[i] > A_max) {
        A_max = A[i];
    }
}

See also