Problem:
Design an algorithm that reads in a set of n single digits and converts them into a single decimal integer. For example, the algorithm should convert the set of 5 digits {2, 7, 4, 9, 3} to the integer 27493
Solution:
package com.myprograms;
import java.util.Scanner;
public class ConvertDigitsToNumber {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.println("how many digits: ");
int n = s.nextInt();
int[] digits = new int[n];
for(int i = 0; i< n; i++){
System.out.println("enter digit");
digits[i] = s.nextInt();
}
s.close();
System.out.println("the number is " + constructTheNumber(digits));
}
private static int constructTheNumber(int[] n){
int number = 0;
for(int i = 0; i< n.length; i++){
number = number * 10 + n[i];
}
return number;
}
}
Output:
how many digits:
5
enter digit
2
enter digit
7
enter digit
4
enter digit
9
enter digit
3
the number is 27493
Design an algorithm that reads in a set of n single digits and converts them into a single decimal integer. For example, the algorithm should convert the set of 5 digits {2, 7, 4, 9, 3} to the integer 27493
Solution:
package com.myprograms;
import java.util.Scanner;
public class ConvertDigitsToNumber {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.println("how many digits: ");
int n = s.nextInt();
int[] digits = new int[n];
for(int i = 0; i< n; i++){
System.out.println("enter digit");
digits[i] = s.nextInt();
}
s.close();
System.out.println("the number is " + constructTheNumber(digits));
}
private static int constructTheNumber(int[] n){
int number = 0;
for(int i = 0; i< n.length; i++){
number = number * 10 + n[i];
}
return number;
}
}
Output:
how many digits:
5
enter digit
2
enter digit
7
enter digit
4
enter digit
9
enter digit
3
the number is 27493
No comments:
Post a Comment