Write your code for Java 7. IT MUST RUN IN ORDER FOR YOUR SUBMISSION TO GET RATE
ID: 3549800 • Letter: W
Question
Write your code for Java 7. IT MUST RUN IN ORDER FOR YOUR SUBMISSION TO GET RATED! I will take it and put it in NetBeans and if there are compile errors I won't give you the points until it's fixed.
http://www.mathjax.org/help/configuration
Explanation / Answer
Problem1.java:
import java.util.Scanner;
public class Problem1 {
public static int number=0;
public static int stringToNumber(String num, int index, int place){
int digit = Integer.parseInt(Character.toString(num.charAt(index)));
number += digit *place;
if (index == 0) {
return number;
}
return stringToNumber(num, --index, place * 10); //recursive call
}
public static void main(String[] args) {
Scanner inp = new Scanner(System.in);
System.out.print("Enter a String of number digits: ");
String num = inp.nextLine();
System.out.println(stringToNumber(num, num.length()-1, 1));
}
}
Problem2.java:
import java.util.Scanner;
public class Problem2{
public static int oddReplaceIndex=-1, temp;
public static void arrange(int arr[], int pos, int size)
{
if(pos==size)
return;
if(arr[pos]%2==0){
temp=arr[oddReplaceIndex+1]; //swapping the odd and even nos
arr[oddReplaceIndex+1]=arr[pos];
arr[pos]=temp;
oddReplaceIndex++; //the next position where swapping will be done
}
arrange(arr, ++pos, size); //recursive call
}
public static void main(String[] args) {
Scanner inp = new Scanner(System.in);
int size;
System.out.println("Enter the size of the arry: ");
size=inp.nextInt();
int[] arr=new int[size];
System.out.println("Enter the elements of the arry: ");
for(int i=0;i<size;i++)
arr[i]=inp.nextInt();
arrange(arr,1,size);
System.out.println("Now, the required array is ");
for(int i=0;i<size; i++)
System.out.print(arr[i]+" ");
}
}
Problem 3:
size-1 recursive calls will happen in every case as once the array has to be traversed, even the last element can be an odd number. So, O(n) is the time complexity