Extracting indivdual digits from a number. - java

I am trying to extracting a individual number from a given integer. example from 1234, I want to store 1 , 2 ,3 ,4 in an array.The number of digits might not be same every time. I don't know how to initialize the array for the same.
int number = 1234;
int [] a = new int[];
for(int i =0;i<lengthOfNum;i++){
a[i] = digitReturn();
}

You can try the following:
int number = 1234;
int length = Integer.toString(number).length();
int[] a = new int[length];
int index = length - 1;
for (int i = 0; i < length; i++){
a[i] = number % 10;
number = number / 10;
index--;
}
Convert the number to String to get the size and use that value to declare the length of the array and then just loop through it, extracting the last number using modulus and then dividing to get rid of the last digit in the integer.

Convert the number into a string, then split the string into an array. After that, convert the characters into integers, like this:
int number = 1234;
List<Integer> digits = ArrayList<Integer>();
String digitsAsString = ("" + number).split("");
for(String digitAsString:digitsAsString){
digits.add(new Integer(Integer.parseInt(digitAsString));
}
Your array of digits is the list of digits

int number = 4567;
String number_string = String.valueOf(number);
char[] chars = number_string.toCharArray();
int[] digits = new int[chars.length];
int i = 0;
for (char c : chars) {
digits[i] = c - '0';
i++;
}

int number = 1234;
String num = Integer.toString(number);
int [] a = new int[num.length()];
for(int i = 0; i < num.length(); i++){
a[i] = Character.getNumericValue(num.charAt(i));
}
First convert number to a String, loop through each char and convert them into an int then storing the value into a.

Related

Printing an integer array in java using for loop, but the first element is always zero

I have been trying for hours to change a user inputted string of numbers into an integer, then create and print an integer array with those integers. I finally got it, but the first element of the printed array is always zero. I don't know how to fix it. I feel like it is really simple, but I am exhausted and am getting stuck on the easiest things. Does anyone know what is wrong? I'll put my code below.
String stringNum = input.nextLine();
int size = stringNum.length();
int[] myArray = new int[size];
for (int a : myArray) {
System.out.print(a);
System.out.print(" ");
for (int i = 0; i < size; i++) {
char n = stringNum.charAt(i);
int intNum = Character.getNumericalValue(n);
myArray[i] = intNum;
}
}
// input: 12345
// output: 0 2 3 4 5
You have mixed up printing the array and populating the array.
First, parse the input string and populate the array
String stringNum = input.nextLine();
int size = stringNum.length();
int[] myArray = new int[size];
for (int i = 0; i < size; i++) {
char n = stringNum.charAt(i);
int intNum = Character.getNumericalValue(n);
myArray[i] = intNum;
}
Then print the elements,
for (int a : myArray) {
System.out.print(a);
System.out.print(" ");
}

conversion of array of decimal string to biginteger

How can I convert array of string containing decimal numbers to big integer?
eg:
String s={"1","2","30","1234567846678943"};
My current code:
Scanner in = new Scanner(System.in);
int n = in.nextInt();
String s[]= new String[n];
for(int i=0; i < n; i++){
s[i] = in.next();
}
BigInteger[] b = new BigInteger[n];
for (int i = 0; i < n; i++) {
b[i] = new BigInteger(String s(i));
}
Here:
b[i] = new BigInteger(String s(i));
should be:
b[i] = new BigInteger(s[i]);
In other words: you got half of your syntax correct; but then seem to forget how to read an already defined array slot:
you use [index] square brackets ( "( )" are only used for method invocations)
No need to specify that "String" type within that expression
Just use new BigInteger(s[i]); instead of new BigInteger(String s(i));
FYI, you don't really have to use a separate String array to store initial values. You can directly store them in BigInteger array. Somewhat like this:
Scanner in = new Scanner(System.in);
int n = in.nextInt();
BigInteger[] b = new BigInteger[n];
for(int i=0; i < n; i++){
b[i] = new BigInteger(in.next());
}

How do I change a given char array of numeric characters in a certain base to an int in that base?

I have a static method that takes in a char[] and an int as its parameters. The char[] array is an array of numeric characters and the int is the radix or base of the number given. I'm trying to convert the char array to an integer type in the given base, but I'm lost on how to do so. So far I created a method that takes in a char[] of a base ten number and converts it to a base 10 int.
Here's what I have so far:
public static int parseInt(char[] valueAsChars, int radix)
{
char[] letters = {'A','B','C','D','E','F'};
String convertedString = "";
int convertedNumber = 0;
int digit = 0;
int counter = 1;
char letter = '0';
// converts array to String
for(int arrayPlace = 0; arrayPlace < valueAsChars.length; arrayPlace++)
{
convertedString = convertedString + valueAsChars[arrayPlace];
}
//converts String to int
for(int stringPlace = convertedString.length() - 1; stringPlace >= 0; stringPlace--)
{
digit = (convertedString.charAt(stringPlace)-'0');
convertedNumber += digit * counter;
counter *= radix;
}
return convertedNumber;
}
How do I do this but with numbers with different bases?
Try to use the existing Java methods:
public static int parseInt(char[] valueAsChars, int radix) {
return Integer.parseInt(new String(valueAsChars), radix);
}

Storing digits of numbers in array

Hello fellow programmers !
I am a beginner with Java and i am looking for a method or a way maybe to store the digits of a 6 digit number entered by the user , in an int array.
For example :-
if the number is 675421.
then i want to store the digits in an array like :-
int[] array = new int[6];
int number = 675421
array[0] = 6;
array[1] = 7;
array[2] = 5;
array[3] = 4;
array[4] = 2;
array[5] = 1;
I want to do so so that i can work with the array to maybe sort or change the order or numbers in array. Thanks!
Here you go,
String temp = Integer.toString(number);
int[] num = new int[temp.length()];
for (int i = 0; i < temp.length(); i++){
num[i] = temp.charAt(i) - '0';
}
for (int i = 0; i < temp.length(); i++) {
System.out.println(num[i]);
}
Edit, after comment
Here, First, you are converting to your number to a string.
Then, take each char out of it(in the loop), subtract the ASCII value of 0 from each char to get the digit [ie, ASCII of 0 is 48, 1 is 49, ... ] (see ASCII table)
Do something like this:
String number = "123123";
int[] intArray = new int[number.length()];
for (int i = 0; i < number.length(); i++)
{
intArray[i] = Integer.parseInt(Character.toString(number.charAt(i)));
}
Hope this helps,
Jason.
Below is the recursive solution
public static void main(String[] args) {
int testNum = 675421;
List<Integer> digitList = new ArrayList<Integer>();
collectDigits(testNum, digitList);
Object[] resultArr = digitList.toArray();
int listSize = resultArr.length;
for (int listCount = 0; listCount < listSize; listCount++) {
System.out.println("result["+listCount+"] = "+resultArr[listCount]);
}
}
private static void collectDigits(int num, List<Integer> digits) {
if (num / 10 > 0) {
collectDigits(num / 10, digits);
}
digits.add(num % 10);
}
One way to do this would be to turn the original integer into a string.
Loop over the string, parsing each character back to an int, and place into the array. Here is an example:
int number = 123456;
String strNumber = number+"";
int[] array = new int[strNumber.length()];
int index = 0;
for(char c : strNumber.toCharArray()){
array[index++] = Integer.parseInt(c+"");
}
System.out.println(Arrays.toString(array));
Math solution, you can split the int number using this:
int[] array = new int[6];
int number = 675421;
array[0] = ((number/100000)%10);
array[1] = ((number/10000)%10);
array[2] = ((number/1000)%10);
array[3] = ((number/100)%10);
array[4] = ((number/10)%10);
array[5] = ((number/1)%10);
If the "number" has a variable length you can automate this, write a coment if you need help

Is there a better (faster) way to divide a number to digits?

I wrote this:
void blah(int num)
{
int numOfDigits = Math.log10(num);
int arr[] = new int[numOfDigits + 1];
for(int i = numOfDigits; i>0; i--)
{
arr[i] = num%10;
num = num/10;
}
}
But I thought there must be a more elegant way of doing this. Is there?
If you're happy with Strings, you could do this:
String[] arr = Integer.toString(num).split("(?<=\\d)");
If you want to go from this to int[]:
int[] arrint = new int[arr.length];
for (int i = 0; i < arr.length; i++)
arrint[i] = Integer.parseInt(arr[i]);
Consider converting the integer to a string using Integer.toString and then using string.toCharArray() and converting back. This may or may not be more 'elegant' depending on your worldview.
This might be one way (i am not super proud about this :))
Integer number = 1234567890; // input number
String temp = number.toString(); // convert to string
int [] output = new int[temp.length()];
for (int i=0 ; i< temp.length(); i++) // get character at index i from string
output[i] = temp.charAt(i) - '0'; // convert it to number by removing '0'

Categories