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

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'

Related

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());
}

Using while loop to determine amount of chars to be created

I am trying to make an application that will reverse a string using a while loop. Just wondering if I am on the right path or not.
So I thought I would make a while loop to determine how many chars i should make. Then I would just print them in reverse in the console.
Here is my code so far. Any help would be appreciated.
// Get the text from the input from the user
// Outputs it to the Text area
// Uses while loop to calculate how many chars to create
String Startword = txfInput.getText();
int LengthOfWord = Startword.length();
int Counter = 1;
while (Counter <= LengthOfWord)
{
// Creates amounts of chars based off the counter
Counter = Counter +1 ;
}
Any suggestions?
Just use a for loop..
String reverse = "";
for (int i = word.length()-1; i>=0; i--)
{
reverse += word.charAt(i);
}
if you want a while... then
while(i >= 0)
{
reverse += word.charAt(i);
i--;
}
You just need to add a character to the reverse String after every iteration, like this:
String Startword = txfInput.getText();
String rev="";
int LengthOfWord = Startword.length();
int Counter = 1;
while (Counter <= LengthOfWord)
{
rev=Startword.charAt(Counter-1)+rev; // Add a character to rev.
Counter = Counter +1 ;
}
System.out.println(rev);
Might be easier to do with a char array:
char[] output = new char[Startword.length];
for(int i = 0; i < Startword.length; i++){
output[i] = Startword.charAt(Startword.length - i - 1);
}
String rev = new String(output);
Scanner input = new Scanner(System.in);
String s=input.nextLine();
char[] stringArray;
stringArray = s.toCharArray();
int temp;
int low=0;
int high=stringArray.length-1;
while(low<high){
temp= stringArray[low];
stringArray[low] = stringArray[high];
System.out.print(stringArray[low]);
low ++;
high--;
}
check this out

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

Repeat an integer n times

I'm trying to make a pyramid out of an integer.
I.E the number 3 :
3
33
333
So based on the answers i found i made this :
int n = 8;
String n2 = Integer.toString(n);
for (int i=0; i<n; i++) {
System.out.println(StringUtils.repeat(n2, i));
}
But it's not working and would be suboptimal. Is there a simple way to repeat an integer n times in the same line ?
EDIT : made myself a method.. not quite happy either but it seems i can't just use something like System.out.println(int x, int n times)
int n = 8;
for (int i=0; i<=n; i++) {
for (int j=0; j<i; j++) {
System.out.print(n + " ");
}
System.out.println("");
}
Ok, you can do this without explicit loops using Java-8 streams:
IntStream.range(1,n).forEach(i -> System.out.println(StringUtils.repeat(n2, i));
or even without apache-commons:
IntStream.range(0,n).forEach(i -> System.out.println(String.join("", Collections.nCopies(i+1, n2))));
But in any case internally all these methods use loops.
I mean isn't it suboptimal to convert my int into a string ? AIn't
there a direct way to deal with the integer ? –
If you dont want to convert int to string.
This may help you.
int n = 3;
for (int i=1; i<=n; i++) {
System.out.println(new String(new char[i]).replace("\0", n+""));
}
Something as below.
public class Test{
public static String repeat(String str, int times) {
return new String(new char[times]).replace("\0", str);
}
public static void main(String[] args) {
for (int i = 1; i < 5; i++) {
System.out.println(repeat("3", i));
}
}
}
Output
3
33
333
3333
You could try to use a StringBuilder.
You would still have to loop, but it might be slightly better performance-wise.
int n = 8;
String n2 = Integer.toString(n);
StringBuilder builder = new StringBuilder(n);
for(int i = 0; i < n; i++) {
builder.append(n2);
System.out.println(builder.toString());
}
This does what you want, but not in the way you think about it. Instead of repeatedly having to create the repeating integer string, we simply build ONE string, saving us the work of repeating it.
To actually answer your question, you could use this code, although I would recomend the first approach:
char[] str = new char[n];
Arrays.fill(str, (char)(number + '0'));
new String(str);
This would only work if your integer is 0 <= number < 10.
To keep with integers, you may store last value each time, and add the next part :
i = 0 --> you get 3
i = 1 --> you get 33 (i0 + 30)
i = 2 --> you get 333 (i1 + 300)
int lastValue = 0;
for (int i=0; i<=n; i++) {
int currentValue = lastValue + (n * Math.pow(10, i));
System.out.println(currentValue);
lastValue = currentValue ;
}
This obviously works for one-digit integers only.

How do I fill an array with consecutive numbers

I would like to fill an array using consecutive integers. I have created an array that contains as much indexes as the user enters:
Scanner in = new Scanner(System.in);
int numOfValues = in.nextInt();
int [] array = new int[numOfValues];
How do i fill this array with consecutive numbers starting from 1?
All help is appreciated!!!
Since Java 8
// v end, exclusive
int[] array = IntStream.range(1, numOfValues + 1).toArray();
// ^ start, inclusive
The range is in increments of 1. The javadoc is here.
Or use rangeClosed
// v end, inclusive
int[] array = IntStream.rangeClosed(1, numOfValues).toArray();
// ^ start, inclusive
The simple way is:
int[] array = new int[NumOfValues];
for(int k = 0; k < array.length; k++)
array[k] = k + 1;
for(int i=0; i<array.length; i++)
{
array[i] = i+1;
}
You now have an empty array
So you need to iterate over each position (0 to size-1) placing the next number into the array.
for(int x=0; x<NumOfValues; x++){ // this will iterate over each position
array[x] = x+1; // this will put each integer value into the array starting with 1
}
One more thing. If I want to do the same with reverse:
int[] array = new int[5];
for(int i = 5; i>0;i--) {
array[i-1]= i;
}
System.out.println(Arrays.toString(array));
}
I got the normal order again..
Scanner in = new Scanner(System.in);
int numOfValues = in.nextInt();
int[] array = new int[numOfValues];
int add = 0;
for (int i = 0; i < array.length; i++) {
array[i] = 1 + add;
add++;
System.out.println(array[i]);
}

Categories