How to convert int value 09 to char array as {'0','9'}? - java

I am working on the problem to find the next greatest number with the same set of digits.
For this I take a integer value input from the user and I want to convert to char array or int array so that I can access individual digits.
But when I take
int value=09 as the input and convert to char array it gives only 9 as it considers it to be octal value. How can I overcome this ?

it is not possible in java to take the int values with leading zeros.
so for the value with leading zeros take it in string format.
but we can insert zeros
int n=7;
String str=String.format("%04d", n); //4 denotes the size of the string
System.out.println(str); // o/p->0007

It is not possible convert a 09 int value to a String of 9 since the value 09 can not be stored in an int.
int is not capable of storing trailing zeros.
Take this sample.
int foo = Integer.valueOf("09");
System.out.println(foo);
Output
9
So to solve your problem you should get a String from the user, validate it and parse it to an Integer[].
Solution
public Integer[] parseToInteger(String number) {
return Arrays.asList(number.toCharArray())
.stream()
.map(c -> Integer.valueOf(c.toString()))
.toArray(size -> new Integer[size]);
}
Now you have an Array of Integer.

Since leading 0's are dropped from integers there is no reason to support assigning such a value to an int.
If I want to convert 9 to '9' I usually just add '0' to it.
You can also do the following:
char c = Character.forDigit(9,10);
If you have a string of characters, you can do the following:
String str = "09";
List<Character> chrs =
str.chars().mapToObj(a -> Character.valueOf((char) a))
.collect(Collectors.toList());
System.out.println(chrs);
Prints
[0,9]

You are asking how to parse a number starting with a leading zero, but I get the feeling that you are actually on the worng track given the problem you are trying to resolve. So let's take one step backward, and lets make sure I understand your problem correctly.
You say that you have to find the "next greatest number with the same set of digits". So you are playing "Scrabble" with digits, trying to find the smalest number composed with the same digits that is strictly greater to the original number. For example, given the input "09", you would output "90", and for "123", you would output "132". Is that right? Let assume so.
Now, the real challenge here is how to determine the smalest number composed with thise digits that is stricly greater to the original number. Actually, there's a few possible strategies:
Enumerate all possible permutations of those digits, then filter out those that are not strictly greater to the original number, and then, among the remaining values, find the smallest value. That would be a very innefficient strategy, requiring both disproportionate memory and processing power. Please, don't consider this seriously (that is, unless you are actually coding for a Quantum Computer ;) ).
Set a variable to the initial number, then iteratively increment that variable by one until you eventually get a number that is composed of the same digits as the original values. That one might look simple to implement, but it actually hides some complexities (i.e. determining that two numbers are composed from the same digits is not trivial, special handling would be required to avoid endless loop if the initial number is actually the greatest value that can be formed with those digits). Anyway, this strategy would also be rather innefficient, requiring considerable processing power.
Iterate over the digits themselves, and determine exactly which digits have to be swapped/reordered to get the next number. This is actually very simple to implement (I just wrote it in less that 5 minutes), but require some thinking first. The algorithm is O(n log n), where n is the length of the number (in digits). Take a sheet of paper, write example numbers in columns, and try to understand the logic behind it. This is definitely the way to go.
All three strategies have one thing in common: they all require that you work (at some point at least) with digits rather than with the number itself. In the last strategy, you actually never need the actual value itself. You are simply playing Scrabble, with digits rather than letters.
So assuming you indeed want to implement strategy 3, here is what your main method might looks like (I wont expand more on this one, comments should be far enough):
public static void main(String[] args) {
// Read input number and parse it into an array of digit
String inputText = readLineFromUser();
int[] inputDigits = parseToDigits(inputText);
// Determine the next greater number
int[] outputDigits = findNextGreaterNumber(inputDigits);
// Output the resulting value
String outputText = joinDigits(outputDigits);
println(outputText);
}
So here's the point of all this discussion: the parseToDigits method takes a String and return an array of digits (I used int here to keep things simpler, but byte would actually have been enough). So basically, you want to take the characters of the input string, and convert that array to an array of integer, with each position in the output containing the value of the corresponding digit in the input. This can be written in various ways in Java, but I think the most simple would be with a simple for loop:
public static int[] parseToDigits(String input) {
char[] chars = input.toCharArray();
int[] digits = new int[chars.length];
for (int i = 0 ; i < chars.length ; i++)
digits[i] = Character.forDigit(chars[i], 10);
return digits;
}
Note that Character.forDigit(digit, radix) returns the value of character digit in base radix; if digit is not valid for the given base, forDigit returns 0. For simplicity, I'm skipping proper validation checking here. One could consider calling Character.isDigit(digit, radix) first to determine if a digit is acceptable, throwing an exception if it is not.
As to the opposite opperation, joinDigits, it would looks like:
public static String joinDigits(int[] digits) {
char[] chars = new char[digits.length];
for (int i = 0 ; i < digits.length ; i++)
chars[i] = Character.digit(digits[i], 10);
return new String(chars);
}
Hope that helps.

Related

How can I zero-pad a hexadecimal digit string to eight digits?

I have a logic requirement, where I need to ensure that a hexadecimal digit string is presented in 8-digit format, even if the leading digits are zero. For example, the string corresponding to 0x3132 should be formatted as "0x00003132".
I tried this:
String key_ip = txt_key.getText();
int addhex = 0;
char [] ch = key_ip.toCharArray ();
StringBuilder builder = new StringBuilder();
for (char c : ch) {
int z = (int) c;
builder.append(Integer.toHexString(z).toUpperCase());
}
System.out.println("\ n (key) is:" + key_ip);
System.out.println("\ nkey in Hex:" + addhex + builder.toString());
, but it gave me an error. Can anyone explain how to fix or rewrite my code for this?
and I want to ask one more thing, if use code
Long.toHexString(blabla);
is it true to change the value "0x00" to "\0030" so that the output of 0 is 30
Evidently, you are receiving a String, converting its chars to their Unicode code values, and forming a String containing the hexadecimal representations of those code values. The problem you want to solve is to left-pad the result with '0' characters so that the total length is not less than eight. In effect, the only parts of the example code that are directly related to the problem itself are
int addhex = 0;
and
System.out.println("\ nkey in Hex:" + addhex + builder.toString());
. Everything else is just setup.
It should be clear, however, that that particular attempt cannot work, because all other considerations aside, you need something that adapts to the un-padded length of the digit string. That computation has no dependency on the length of the digit string at all.
Since you're already accumulating the digit string in a StringBuilder, it seems sensible to apply the needed changes to it, before reading out the result. There are several ways you could approach that, but a pretty simple one would be to just insert() zeroes one at a time until you reach the wanted length:
while (builder.length() < 8) {
builder.insert(0, '0'); // Inserts char '0' at position 0
}
I do suspect, however, that you may have interpreted the problem wrongly. The result you obtain from doing what you ask is ambiguous: in most cases where such padding is necessary, there are several input strings that could produce the same output. I am therefore inclined to guess that what is actually wanted is to pad the digits corresponding to each input character on a per-character basis, so that an input of "12" would yield the result "00310032". This would be motivated by the fact that Java char values are 16 bits wide, and it would produce a transformation that is reliably reversible. If that's what you really want, then you should be able to adapt the approach I've presented to achieve it (though in that case there are easier ways).
if use code
Long.toHexString(blabla);
is it true to change the value "0x00" to "\0030" so that the output of
0 is 30
The Unicode code value for the character '0', expressed in hexadecimal, is 30. Your method of conversion would produce that for the input string "0". Your method does not lend any special significance to the character '\' in its input.

How to represent a 5 letter string as digit?

I want to create a numerical representation of 5 letter codes. The codes may have 1-5 letters or digits.
The number must of course be unique. It is not absolutely necessairy that those numbers can be converted back to the ascii.
Thus I need digits from 0 to ZZZZZ
The resulting number size should be as small as possible.
I started with the following, but it's not quite what I want:
String a="ZZZZZZ";
for (int i = 0; i < a.length(); ++i) {
System.out.print(a.charAt(i)-'A'+1);
}
ZZZZZZ=262626262626
000000=-16-16-16-16-16-16
Start by enumerating all possible "digits" of your number:
Ten decimal digits 0 through 9
Twenty six letters A through Z
You have 36 possible "digits" for five positions, so the max number is 365=60,466,176. This number fits in an int.
You can make this number by calling Integer.parseInt, and passing a radix of 36:
System.out.println(Integer.parseInt("ABZXY", 36)); // 17355958
Demo.
Keep in mind that A134Z is already a number; it is only printed in Base-36 representation!
Albeit being just one sentence, the above should give you all you need to know to translate any 5-character string with 0-9 and A-Z into a number (and back).
Simplest solution - if letters are case insensitive is to use radix of 36 - full alphabet plus 10 digits. That way you get both functions for free - converting from string to long and from long to string like this:
long numericCode = Long.parseLong("zzzzz", 36); // gives 60466175
String stringCode = Long.toString(numericCode, 36); // gives "zzzzz"
You can treat the string as a number in base36 (where A=10, B=11 ... Z=35). This way, you will use exactly the numbers from 0 to 36^5-1, and each will be used exactly once.

Issues With length() And Multiples Of 3

If you get the length of a String using length(), the String always being multiples of 3 (in my case: "1.02.03.04.05.06.07.0 etc.").
Each 3 characters representing a letter, with .1 indicating a capital letter.
How do you use the length to find how many sequences of three there are in the String, for each instance of said String (each time being another multiple of 3)?
Edit:
Yes to Burrito's question, I am looking to find the number of 3 character blocks in each unique String.
It's pretty simple. Next time please show the working of your code.
public int findMultiplesOf3(String value)
{
return (value.length()/3);
}
Edit
Any length of the string which is less than 3 or not divisible by 3, the return value will only be a whole number. (For Ex 22/3 = 7.333 But the return value would be 7) Since we are returning an int (integer) value in the function header.

Converting Roman Numeral to integer value? [duplicate]

This question already has answers here:
Converting Roman Numerals To Decimal
(30 answers)
Closed 8 years ago.
I'm a new programming student and my assignment is to convert the input of a Roman Numeral to it's integer value. Here is what I have been given:
Write a program that converts a Roman number such as MCMLXXVIII to its decimal number representation. This program must have 3 methods and a main method!
Write a method that takes input from the user and passes it to a conversion method.
Write a method that yields the numeric value of each of the letters (conversion method).
Write a method that outputs the number the user entered and the converted number.
Write a main method to test the 3 methods.
HINT: Use a single dimensional array!
Convert a string as follows:
• Look at the first two characters. If the first has a larger value than the second, then simply convert the first.
• Call the conversion method again for the substring starting with the second character.
• Add both values. o If the first one has a smaller value than the second, compute the difference and add to it the conversion of the tail.
Now I am struggling trying to figure out what to do for my conversion method. Here is what I have written so far:
public static String romanInput(String number) {
Scanner numberInput = new Scanner (System.in);
System.out.print("Enter a roman numeral: ");
String userInput = numberInput.next();
return userInput;
}
public static int numberConversion(int number) {
int romanConv = 0;
char[] romanChar = {1, 5, 10, 50, 100, 500, 1000};
for (int i = 0; i < romanChar.length; i++)
}
You could see that I have already written the method that takes the input from a user. I think I did this correctly. However, I don't know what to do for this conversion method. It says to use a single dimensional array so that's what I did over here:
char[] romanChar = {1, 5, 10, 50, 100, 500, 1000};
Those are supposed to be the values of I, V, X, L, C, D, and M. I'm really just confused as where to go from there and I would appreciate it if someone can help me out.
The Roman numeration is non-positional, meaning that the value of the digits does not depend on their position and you can ignore the latter. Then it suffices to add the values of all digits.
There is an exception anyway: if a digit immediately precedes a digit of a higher value, then it is subtracted instead of added.
So the processing is simply:
Clear an accumulator.
Read the digits from left to right. For new every digit, convert it to its value and add it to the accumulator. In the end the accumulator contains the number value.
To handle the exception, you can use the following trick:
Use a variable that holds the value of the previous digit (initially set to the value of M);
when the current digit has a higher value than the previous, you must correct the accumulator by subtracting twice the value of the previous.
Programmatically:
( Initialize )
Prv= 1000
Acc= 0
Loop:
( Accumulate )
Cur= Lookup(Digit[i])
Acc+= Cur
( Adjust for inversions )
if Prv < Cur -> Acc-= 2 * Prv
Prv= Cur
For instance, CXIX gives
Prv Cur Acc
C 1000 100 100
X 100 10 110
I 10 1 111
X 1 10 121-2*1 = 119
If I were you, I would begin by taking one baby step at a time. For example, if the only input I have to worry about is "I", then what? That is trivial of course.
Next, if the input is "II", then what? This suggests that I need to process the input one character at a time. Both the "I"s are equal to one each, and the result is the sum of the two. That means, I must have a "result" or some such variable, initialized to zero, and then for each character from the input string (I, then I), convert that to its numeric value (1, and then 1), add them up and return the value.
This logic works well for "III" also.
But then you face your first challenge with "IV". That is not trivial, specially if you are new to such an algorithm. Let me keep it aside, with a note that that is tough so will deal with this later.
The values "V", "VI", "VII", "VIII" all work fine with the above logic.
But then again I would be stuck with "IX". Similar to "IV" above. Maybe I have an idea about these two now, but then, maybe I'll still keep both these aside for the time being.
This works fine for "X", "XI", "XII", "XIII", and then again problem with "XIV".
I'll resist the temptation to solve the problems of "IV", "IX", "XIV" so that you can try them yourself; remember these are non-trivial, at least compared to what I have written above. Try it out.
So you see, incremental addition works well, but reduction is an unresolved problem.
Hope this helps.

Is there a nice way to pad an Integer with zeroes without converting it to a String?

I can't think of a better way to left pad an integer with zeroes without first converting it to a String. Is there a way to do this? I've found numerous questions regarding this but they all require a String conversion. I understand we can find the length with this approach:
int length = (num==0) ? 1 : (int)Math.log10(num) + 1;
However, this will still require me to convert it to a String and back afterwards. Surely, there's a better way?
No. An int represents a mathematical integer value, represented as 32 bits. The number 0001 is 1, and has a unique binary representation. Left-padded integers are not integers. they are Strings.
No. Numeric types cannot contain leading zeros. This a feature of the formatted textual representation i.e. Strings
Since you already have the length I'm guessing the leading zero's are simply for output, but ultimately your question was answered by the other two posters.
int length = (num==0) ? 1 : (int)Math.log10(num) + 1;
String zeros;
for(int i=0; i<length; i++) {
zeros = zeros.concat("0");
}
System.out.println(zeros + num);

Categories