I'm trying to convert a integer number to an array of chars without using String operations.
My attempt was:
int number = 12;
char[] test = Character.toChars(number);
for (char c : test)
System.out.println(c);
There is no output, and should give me:
'1'
'2'
How can I fix this? Thank you!
Try something like this:
int number = 12345;
char[] arr = new char[(int) (Math.log10(number) + 1)];
for (int i = arr.length - 1; i >= 0; i--) {
arr[i] = (char) ('0' + (number % 10));
number /= 10;
}
System.out.println(Arrays.toString(arr));
[1, 2, 3, 4, 5]
Note that floor(log10(n) + 1) returns the number of digits in n. Also, if you want to preserve your original number, create a copy and use that in the for-loop instead.
Also note that you might have to adapt the code above if you plan on also handling non-positive integers. The overall idea, however, should remain the same.
char[] test = Integer.toString(number).toCharArray();
Extract each digit of the number, convert it into a character(by adding '0') and store them into a char array. Let us know what you have tried.
+1 for #arshajii's code log10(n) + 1 is something new for me as well. If you intend to use Vectors instead of arrays you can also follow this procedure(But the Vector has elements in reverse order) in which you never need to calculate the size of number itself
public static Vector<Character> convert(int i) {
Vector<Character> temp = new Vector<Character>();
while (i > 0) {
Character tempi = (char) ('0' + i % 10);
i = i / 10;
temp.add(tempi);
}
return temp;
}
Related
Is there a better(Faster) way to split a binary string into an Array?
My code That loops and substring every 8 characters in one element.
binary = my binary string(Huge) : "1010101011111000001111100001110110101010101"
int index = 0;
while (index < binary.length()) {
int num = binaryToInteger(binary.substring(index, Math.min(index + 8,binary.length())));
l.add( num);
temp = temp+ String.valueOf(num);
index += 8;
}
What I am trying to do is to split my binary string into pieces of 8 characters 10101010 and then get the int value of the 8 characters and will store that in arraylist witch in this case was l
My code is working but is very time consuming.. Is there a faster way of getting this done?
It's easy using regex:
binary.split("(?<=\\G.{8})");
However, it creates an array of strings. I don't get your will of creating an array of integers, since binary strings don't fit into this type (they can start with "0" and they can be really long).
I think there are mutiple options using Regex, substring, split etc available in java or Google Guavas - Splitter.fixedLength().
Splitter.fixedLength(8).split("1010101011111000001111100001110110101010101");
This Split a string, at every nth position clearly explain the performance of various functions.
It would probably faster using toCharArray:
Long time = System.currentTimeMillis();
List<Integer> l = new ArrayList<>();
int index = 0;
String binary =
"1010101011111000001111100001110110101";
char[] binaryChars = binary.toCharArray();
while (index < binaryChars.length) {
int num = 0;
for (int offset = 0; offset < Math.min(8, binary.length() - index); offset++) {
int bo = index + offset;
if (binaryChars[bo] == '1') {
num += Math.pow(2, offset + 1);
}
}
l.add(num);
index += 8;
}
System.out.println(System.currentTimeMillis() - time);
Since you want to split into groups of eight bits, I guess, you want to decode bytes rather than ints. This is easier than you might think:
String binary = "1010101011111000001111100001110110101010101";
byte[] result=new BigInteger(binary, 2).toByteArray();
Maybe you can try making a for-each loop to go through each character in the string, combine them into 8-bit values and convert into bytes. I don't know if that will be faster, just a suggestion.
for (char c : binary.toCharArray() ) { do stuff }
If I have a string and an int, I want to be able to create a loop that will print the first char of the string, followed by each the char at value of that int.
e.g. If I have the word "Miracle" and the int 2, the result should be "Mrce". My code does this, but stops a char short for certain words.
System.out.println(str.charAt(0));
while (n <= str.length())
{
System.out.println(str.charAt(n));
n = n+n;
}
This works for strings like "abcdefg" and int 3. It prints "adg", but if the string is "miracle" and int 2, it prints "mrc" and not "mrce".
I'm pretty sure the problem is in the "n= n+n" statement.
Because if the int is 3 and the string is greater than 3 it will loop, but in the n=n+n statement it will loop enough that n will be greater than str length and it halts.
How can I correct this?
You are right, your problem is with n=n+n because it multiple n with 2 in every step so you must change that.
change your code like this :
int m = 0;
while (m < str.length())
{
System.out.println(str.charAt(m));
m = m+n;
}
n = n+n; means that in each iteration you are multiplying your n by 2, so
iteration | n
----------+-------
1 | 3
2 | 3+3=6
3 | 6+6=12
and so on.
What you need is temporary variable (iterator) which will use n but will not change it.
Generally more readable way to write it would be with for loop like
for (int i = 0; i < str.length(); i = i+n){//or `i += n`
^^^^^^^^^ ^^^^^^^^^^^^^^^^ ^^^^^^^
// start at continue when in next step
System.out.print(str.charAt(i));
}
I'll answer with a counterquestion: where is this mentionned int? What walue should it have, and what value does it have?
In short, you should have one variable which has the step value and another variable which acts as a cursor.
Something like
int cursor = 0;
while (cursor <= str.length()) {
System.out.println(str.charAt(cursor));
cursor += stepValue;
}
Here you see that it is necessary to have two distinct variables here.
It is working for first few instances as 2+ 2 = 4, but after that - its doing 4 + 4 = 8, while you need is 4 + 2 = 6.
Take a new var (v), assign it the initial value, & instead of doing n = n + n, do
n = n + v
I think this is what you need
int n = 0;
int skip = 2;
while (n < str.length())
{
System.out.println(str.charAt(n));
n+=skip;
}
First of all, you have an error here:
n <= str.length()
It should be
n < str.length()
because strings are indexed from 0 to length-1.
Also make sure you are indexing from 0, not from 1.
Another thing is that you are adding a bigger number each time. So yes - you are right about n+n - it's wrong.
You should do something like this:
n = ...;
for (int i = 0; n * i < str.length(); ++i)
{
int index = n * i;
System.out.println(str.charAt());
}
This way you have n * 0, n * 1, n * 2, ..., which is what you want.
There are two things wrong in your code:
If n == str.length(), it will throw an exception, as it tries to
access str.charAt(n), which in that case doesn't exist.
Another thing, n = n + n will change the value of n every time, so you
will add a bigger number every time instead of the same.
You could use a for-loop for a cleaner approach though:
for (int i = 0; i < str.length(); i += n) {
System.out.println(str.charAt(i));
}
I'm new on this site and, if I'm here it's because I haven't found the answer anywhere on the web and believe me: I've been googling for quite a time but all I could find was how to convert a number to an array not the other way arround.
I'm looking for a simple way or function to convert an int array to an int number. Let me explain for example I have this :
int[] ar = {1, 2, 3};
And I want to have this:
int nbr = 123;
In my head it would look like this (even if I know it's not the right way):
int nbr = ar.toInt(); // I know it's funny
If you have any idea of how I could do that, that'd be awesome.
Start with a result of 0. Loop through all elements of your int array. Multiply the result by 10, then add in the current number from the array. At the end of the loop, you have your result.
Result: 0
Loop 1: Result * 10 => 0, Result + 1 => 1
Loop 2: Result * 10 => 10, Result + 2 => 12
Loop 3: Result * 10 >= 120, Result + 3 => 123
This can be generalized for any base by changing the base from 10 (here) to something else, such as 16 for hexadecimal.
You have to cycle in the array and add the right value.
The right value is the current element in the array multiplied by 10^position.
So: ar[0]*1 + ar[1]*10 + ar[2] *100 + .....
int res=0;
for(int i=0;i<ar.length;i++) {
res=res*10+ar[i];
}
Or
for(int i=0,exp=ar.length-1;i<ar.length;i++,exp--)
res+=ar[i]*Math.pow(10, exp);
First you'll have to convert every number to a string, then concatenate the strings and parse it back into an integer. Here's one implementation:
int arrayToInt(int[] arr)
{
//using a Stringbuilder is much more efficient than just using += on a String.
//if this confuses you, just use a String and write += instead of append.
StringBuilder s = new StringBuilder();
for (int i : arr)
{
s.append(i); //add all the ints to a string
}
return Integer.parseInt(s.toString()); //parse integer out of the string
}
Note that this produce an error if any of the values past the first one in your array as negative, as the minus signs will interfere with the parsing.
This method should work for all positive integers, but if you know that all of the values in the array will only be one digit long (as they are in your example), you can avoid string operations altogether and just use basic math:
int arrayToInt(int[] arr)
{
int result = 0;
//iterate backwards through the array so we start with least significant digits
for (int n = arr.length - 1, i = 1; n >= 0; n --, i *= 10)
{
result += Math.abs(arr[n]) * i;
}
if (arr[0] < 0) //if there's a negative sign in the beginning, flip the sign
{
result = - result;
}
return result;
}
This version won't produce an error if any of the values past the first are negative, but it will produce strange results.
There is no builtin function to do this because the values of an array typically represent distinct numbers, rather than digits in a number.
EDIT:
In response to your comments, try this version to deal with longs:
long arrayToLong(int[] arr)
{
StringBuilder s = new StringBuilder();
for (int i : arr)
{
s.append(i);
}
return Long.parseLong(s.toString());
}
Edit 2:
In response to your second comment:
int[] longToIntArray(long l)
{
String s = String.valueOf(l); //expand number into a string
String token;
int[] result = new int[s.length() / 2];
for (int n = 0; n < s.length()/2; n ++) //loop through and split the string
{
token = s.substring(n*2, (n+2)*2);
result[n] = Integer.parseInt(token); //fill the array with the numbers we parse from the sections
}
return result;
}
yeah you can write the function yourself
int toInt(int[] array) {
int result = 0;
int offset = 1;
for(int i = array.length - 1; i >= 0; i--) {
result += array[i]*offset;
offset *= 10;
}
return result;
}
I think the logic behind it is pretty straight forward. You just run through the array (last element first), and multiply the number with the right power of 10 "to put the number at the right spot". At the end you get the number returned.
int nbr = 0;
for(int i = 0; i < ar.length;i++)
nbr = nbr*10+ar[i];
In the end, you end up with the nbr you want.
For the new array you gave us, try this one. I don't see a way around using some form of String and you are going to have to use a long, not an int.
int [] ar = {2, 15, 14, 10, 15, 21, 18};
long nbr = 0;
double multiplier = 1;
for(int i = ar.length-1; i >=0 ;i--) {
nbr += ar[i] * multiplier;
multiplier = Math.pow(10, String.valueOf(nbr).length());
}
If you really really wanted to avoid String (don't know why), I guess you could use
multiplier = Math.pow(10,(int)(Math.log10(nbr)+1));
which works as long as the last element in the array is not 0.
Use this method, using a long as your input is to large for an int.
long r = 0;
for(int i = 0; i < arr.length; i++)
{
int offset = 10;
if(arr[i] >= 10)
offset = 100;
r = r*offset;
r += arr[i];
}
This checks if the current int is larger than 10 to reset the offset to 100 to get the extra places required. If you include values > 100 you will also need to add extra offset.
Putting this at end of my post due to all the downvotes of Strings...which is a perfectly legitimate answer...OP never asked for the most efficient way to do it just wannted an answer
Loop your array appending to a String each int in the array and then parse the string back to an int
String s = "";
for(int i = 0; i < arr.length; i++)
s += "" + arr[i];
int result = Integer.parseInt(s);
From your comment the number you have is too long for an int, you need to use a long
String s = "";
for(int i = 0; i < arr.length; i++)
s += "" + arr[i];
long result = Long.parseLong(s);
If you can use Java 1.8, stream API makes it very simple:
#Test
public void arrayToNumber() {
int[] array = new int[]{1,2,3,4,5,6};
StringBuilder sb = new StringBuilder();
Arrays.stream(array).forEach(element -> sb.append(element));
assertThat(sb.toString()).isEqualTo("123456");
}
you can do it that way
public static int[] plusOne(int[] digits) {
StringBuilder num= new StringBuilder();
PrimitiveIterator.OfInt primitiveIterator = Arrays.stream(digits)
.iterator();
while (primitiveIterator.hasNext()) {
num.append(primitiveIterator.nextInt());
}
int plusOne=Integer.parseInt(String.valueOf(num))+1;
return Integer.toString(plusOne).chars().map(c -> c-'0').toArray();
}
BE SIMPLE!!!
public static int convertToInteger(int... arr) {
return Integer.parseInt(Arrays.stream(arr)
.mapToObj(String::valueOf)
.collect(Collectors.joining()));
}
this also possible to convert an Integer array to an int array
int[] result = new int[arr.length];
for (int i = 0; i < arr.length; i++) {
result[i] = arr[i].intValue();
}
e.g. for int n = 1234 I could create a string (s.valueOf(n)), then I would define the array like this:
int[] array = new int[s.length()]; //this allocates memory for an array with 4 elements
Is there any other way to do this without using a string and only integers?
You can use Math#log10 to find the number of digits.
numOfDigits = (int)(Math.log10(n)+1);
Now you do:
int[] array = new int[numOfDigits];
Note that if n = 1999, numOfDigits will be 4. So you're allocating a memory for 4 integers and not 1999 integers.
But be careful, while reading the documentation of the method, you'll note:
If the argument is positive zero or negative zero, then the result is
negative infinity.
I assume you are talking about Java, so:
int value = myValue;
for (int noOfDigits = 1; Math.abs(value) >= 1; ++noOfDigits) {
value /= 10;
}
int[] array = new int[noOfDigits];
This does not include space for the leading sign if the number is negative, but you can easily test this condition and increment noOfDigits by one.
Use log function to find the no. of digits.
int size = (int)Math.log10(1234)+1;
int[] array = new int[size];
According to my understanding you can do the following to get count of digits
int n = 12345;
int count = 1;
while(n>10){
n = n/10;
count++;
}
int[] array = new int[count];
if (n>0){
numberOfDigets = (int)(Math.log10(n)+1);
}
else if (n < 0){
numberOfDigets = (int)(Math.log10(Math.abs(n))+1);
} else {
numberOfDigets = 1;
}
If n is bigger then zero use the Math.log10 function as Maroun Maroun wrote. If the n is less the zero use the Math.abs function to get a positiv value. If you want to allocate space for the - the add 2 instead of 1. The else clause is for the case when n is zero and sets numberOfDigets to 1.
If an extra call to a java function don't matter use this code.
if (n != 0){
numberOfDigets = (int)(Math.log10(Math.abs(n))+1);
} else {
numberOfDigets = 1;
}
Math.abs(n) will always return a positiv version of n. The value to watch out for is the Integer.min_value beacuse that value will still be negativ, but that is another question.
is there a way in Java to convert an Integer to single digits, and vice versa. Like this:
So I have the number 345. I want to break it down to 3, 4 and 5 - three seperate numbers.
I have the numbers 3, 4 and 5. I want to put them together to make 345?
You would have to use a combination of mod and divide.
Here is a short method -
public void integerToSingleDigit(int number){
while (number > 0) {
System.out.print(number % 10 + " "); // get u the right most single digit
number = number / 10; // remove the single digit from the right
}
}
Well you can easily convert it to a character array, and go from there:
char[] parts = Integer.toString(value).toCharArray();
int[] digits = new int[parts.length];
for (int i = 0; i < parts.length; i++) {
digits[i] = parts[i] - '0';
}
(You don't really need the char array here - you could just use the string and use length() and charAt() instead of length and the indexer - but I find this clearer.)
Then to reassemble, just do the reverse - create a char[] from the digits (by adding '0' to each), then create a string from the char[], then use Integer.parseInt.
The simplest way would be the following
for (char c : String.valueOf(numberToSplit).toCharArray()) {
int digit = Character.getNumericValue(c);
}