How to delete specific digit from integer? - java

In the n integer where n = 1237534 (for example) I have to delete digit 3 so I can get the biggest value possible. n can be negative number also.
I can get 127534 or 123754.
The bigger is of course 127534, but how can I return it?
I've tried something like this:
int n = 1237534;
String newNum = String.valueOf(n);
int[] newGuess = new int[newNum.length()];
for (int i = 0; i < newNum.length(); i++) {
newGuess[i] = newNum.charAt(i) - '0';
}
StringBuilder sb = new StringBuilder();
for (int i = 0; i < newGuess.length; i++) {
if (!(newGuess[i] % 3 == 0)) {
sb.append(newGuess[i]);
}
}
System.out.println(sb);
I get 12754 which is not correct answer. Anyone maybe have an idea how to solve it?

This does not require arrays nor loops:
int n = 1237534;
String newNum = String.valueOf(n);
char c = '3';
StringBuilder sb1 = new StringBuilder( newNum );
StringBuilder sb2 = new StringBuilder( newNum );
int newGuess1 = Integer.parseInt(sb1.deleteCharAt(newNum.indexOf(c)).toString());
int newGuess2 = Integer.parseInt(sb2.deleteCharAt(newNum.indexOf(c, newNum.indexOf(c)+1)).toString());
System.out.println( newGuess1 > newGuess2 ? newGuess1: newGuess2 );

Here is an alternative approach that also checks to ensure that the number actually contains the digit. Otherwise, an exception could be thrown if the index returns -1.
The method simply deletes the first or last occurrence of the digit depending on whether the number is negative or not.
int n = 1234321;
int bad_digit = 3;
StringBuilder sb = new StringBuilder(Integer.toString(n));
String bad = Integer.toString(bad_digit);
int idxOfFirst = sb.indexOf(bad);
// first, make certain the number contains the digit.
if (idxOfFirst >= 0) {
if (sb.charAt(0) == '-') {
// if negative, delete last character to give the larger value
sb.deleteCharAt(sb.lastIndexOf(bad));
} else {
// else delete the first character to give the larger value
sb.deleteCharAt(idxOfFirst);
}
}
System.out.println(sb);
This prints the string rather than convert to an integer since printing an integer results in conversion to a string anyway. If the digit does not appear in the original number, then the original is printed. You can alter that handling to meet your requirements.

How about this:
int n = 123454321;
int bad_digit = 3;
StringBuilder s = new StringBuilder(n + "");
s.reverse();
System.out.println("Reversed String: " + s);
for (int i = 0; i < s.length(); i++) {
// Check if the character at index 'i' and the
// digit are equal, by converting both to strings
if (("" + s.charAt(i)).equals("" + bad_digit)) {
s.replace(i, i + 1, "");
break;
}
}
System.out.println("Reversed String after removing the digit (if found): " + s);
s.reverse();
System.out.println("Greatest number without the bad digit: " + s);
Basically, we need to remove the last occurrence of the digit to be removed (the bad_digit). So we convert the number to a string and reverse it. Now we need to remove the first occurrence of the digit. So we iterate over the characters, and when we find that digit, we remove it from the string, and exit the loop. Now we reverse the string again, and the output is what you want.

Related

Java: converting each letter into the number for example a = 1, b = 2, c = 3

char[] alphabet = {'a','b','c','d','e','f','g','h','i','j','k','l'...};
int number = 0;
char input = console.nextLine().charAt(0);
for (int i = 0; i <= 24; i++) {
if(Character.isLetter(alphabet[i])) {
number = i;
}
}
System.out.println(number);
I want each letter to be converted into a number for example
a = 1; b = 2; c = 3... and so on.
but it keeps turning 'number' into 10 for some reason
help pls
my code is a complete mess
To store key - value pairs, you can use a map. An example of a key value pair would be 'a' and 1.
Create a map and populate it with your key value pairs.
Map<Character, Integer> letterMap = new HashMap<>();
letterMap.put('a', 1);
letterMap.put('b', 2);
...
Afterwards, you can retrieve the value for the character with a simple "get" operation.
char input = console.nextLine().charAt(0);
if(Character.isLetter(input)) {
int number = letterMap.get(input); //Simple get operation
System.out.println(number);
} else {
System.out.println("You did not input a lowercase letter.");
}
You can simply do like this
char ch = 'z';
int position = ch - 'a' + 1;
System.out.print(position);
You need to be clearer in what you are trying to accomplish. What do you want to do with these numerical positions of alphabet letters? Are you obtaining user input? Something like this may be what you're looking for:
Scanner keyboard = new Scanner(System.in);
String alphabet = "abcdefghijklmnopqrstuvwxyz";
System.out.println("Enter string: ");
String input = "";
while(keyboard.hasNextLine()) {
input += keyboard.nextLine().toLowerCase();
}
for(int i = 0; i < input.length(); i++) {
System.out.print(alphabet.indexOf(input.charAt(i))+1+" ");
}
Since the characters are in order in the ASCII character set, just subtract a from each and add 1.
char[] alphabet = {'a','b','c','d','e','f','g','h','i','j','k','l'};
for (char c : alphabet) {
System.out.println(c - 'a' + 1);
}

How to calculate the consecutive sum of number in a string?

I would like to find the sum of integer in string. For example:
String myString= "The price is 345and the tax1 is 12sales";
String output = "The price is 12and the tax1 is 3sales";
I found few approaches none is displaying the final output the way I need.
int sum = 0;
for (int I =0; i < myString.lengh(); i++)
{
char c = myString.charAt(i);
if(Character.isDigit(c))
{
int value = Integer.parseInt(String.valueOf(c));
}
}
I am getting the total sum but I would like to be able to append the string with individual sums.
output = "The price is 12and the tax1 is 3sales"
I'm using a StringBuilder for building the result string. You have to keep adding the digits as long as you encounter digits. When you encounter a character, you have to append the sum at hand (if you have) and then append the character.
Note: This won't work if the sum can be 0 (and needs to be tweaked to support that).
int sum = 0;
StringBuilder builder = new StringBuilder();
for (int i = 0; i < myString.length(); i++)
{
char c = myString.charAt(i);
if(Character.isDigit(c))
{
sum += Integer.parseInt(String.valueOf(c));
} else {
if (sum != 0) {
builder.append(sum);
}
builder.append(c);
sum = 0; //reset
}
}
add an if statement checking the next character for a digit, if it's a digit add it, otherwise you are done and can print it.
However, your input is quite unusual, are you sure you can not improve the input itself?

License Key Formatting code Challenge Leetcode

This is the challenge:
You are given a license key represented as a string S which consists only alphanumeric character and dashes. The string is separated into N+1 groups by N dashes. Given a number K, we would want to reformat the strings such that each group contains exactly K characters, except for the first group which could be shorter than K, but still must contain at least one character. Furthermore, there must be a dash inserted between two groups and all lowercase letters should be converted to uppercase. Given a non-empty string S and a number K, format the string according to the rules described above.
Example 1:
Input: S = "5F3Z-2e-9-w", K = 4 Output: "5F3Z-2E9W" Explanation: The string S has been split into two parts, each part has 4 characters.
Note that the two extra dashes are not needed and can be removed.
Example 2:
Input: S = "2-5g-3-J", K = 2 Output: "2-5G-3J" Explanation: The string S has been split into three parts, each part has 2 characters except the first part as it could be shorter as mentioned above.
Note:
1) The length of string S will not exceed 12,000, and K is a positive integer.2) String S consists only of alphanumerical characters (a-z and/or A-Z and/or 0-9) and dashes(-).
3) String S is non-empty.
Here is my Code:
public static String licenseKeyFormatting(String S, int Key) {
String cleaned = S.replaceAll("[\\-]", "").toUpperCase();
String result = "";
int currentPos = 0;
//IF EVENLY SPLIT
if ( (cleaned.length() % Key) == 0 ) {
int numGroups = cleaned.length()/Key;
for(int i = 0; i < numGroups; i++) {
for (int k =0; k < Key; k++) {
char currentLetter = cleaned.charAt(currentPos++);
result = result + currentLetter;
}
if (i != (numGroups - 1)) {
result = result + "-";
}
}
}
else {
int remainder = cleaned.length() % Key;
for (int i = 0; i < remainder; i++) {
char currentLetter = cleaned.charAt(currentPos++);
result = result + currentLetter;
}
if(remainder == cleaned.length()) {
return result;
}
else {
result = result + "-";
}
int numGroups =( (cleaned.length() - remainder)/Key);
for (int i = 0; i < numGroups; i++) {
for (int k =0; k < Key; k++) {
char currentLetter = cleaned.charAt(currentPos++);
result = result + currentLetter;
}
if (i != (numGroups - 1)) {
result = result + "-";
}
}
}
//IF NOT EVENLY SPLIT
return result;
}
When I run it on my Computer, it works perfectly. When I run it on leetcode, it gives me a "Time Limit Exceeded" Error on the an input of a string of 44151 characters and "1" as the key. When I run the same input on my IDE, it works fine, but not on LeetCode. What might be the error? How could I make this more efficient?
I believe there is nothing wrong in program, but it is not the fast enough to meet time complexity expected by leetcode. I would suggest you can try, remove dashes and convert to upper cases. then add dashes at every (kth+remainder) places after the remainder position.
Do these operations in a stringbuilder instead of string.

Unsure how to implement for loop

Hello I am having trouble implementing this function
Function:
Decompress the String s. Character in the string is preceded by a number. The number tells you how many times to repeat the letter. return a new string.
"3d1v0m" becomes "dddv"
I realize my code is incorrect thus far. I am unsure on how to fix it.
My code thus far is :
int start = 0;
for(int j = 0; j < s.length(); j++){
if (s.isDigit(charAt(s.indexOf(j)) == true){
Integer.parseInt(s.substring(0, s.index(j))
Assuming the input is in correct format, the following can be a simple code using for loop. Of course this is not a stylish code and you may write more concise and functional style code using Commons Lang or Guava.
StringBuilder builder = new StringBuilder();
for (int i = 0; i < s.length(); i += 2) {
final int n = Character.getNumericValue(s.charAt(i));
for (int j = 0; j < n; j++) {
builder.append(s.charAt(i + 1));
}
}
System.out.println(builder.toString());
Here is a solution you may like to use that uses Regex:
String query = "3d1v0m";
StringBuilder result = new StringBuilder();
String[] digitsA = query.split("\\D+");
String[] letterA = query.split("[0-9]+");
for (int arrIndex = 0; arrIndex < digitsA.length; arrIndex++)
{
for (int count = 0; count < Integer.parseInt(digitsA[arrIndex]); count++)
{
result.append(letterA[arrIndex + 1]);
}
}
System.out.println(result);
Output
dddv
This solution is scalable to support more than 1 digit numbers and more than 1 letter patterns.
i.e.
Input
3vs1a10m
Output
vsvsvsammmmmmmmmm
Though Nami's answer is terse and good. I'm still adding my solution for variety, built as a static method, which does not use a nested For loop, instead, it uses a While loop. And, it requires that the input string has even number of characters and every odd positioned character in the compressed string is a number.
public static String decompress_string(String compressed_string)
{
String decompressed_string = "";
for(int i=0; i<compressed_string.length(); i = i+2) //Skip by 2 characters in the compressed string
{
if(compressed_string.substring(i, i+1).matches("\\d")) //Check for a number at odd positions
{
int reps = Integer.parseInt(compressed_string.substring(i, i+1)); //Take the first number
String character = compressed_string.substring(i+1, i+2); //Take the next character in sequence
int count = 1;
while(count<=reps)//check if at least one repetition is required
{
decompressed_string = decompressed_string + character; //append the character to end of string
count++;
};
}
else
{
//In case the first character of the code pair is not a number
//Or when the string has uneven number of characters
return("Incorrect compressed string!!");
}
}
return decompressed_string;
}

Adding space between characters

I want to add space after every two chars in a string.
For example:
javastring
I want to turn this into:
ja va st ri ng
How can I achieve this?
You can use the regular expression '..' to match each two characters and replace it with "$0 " to add the space:
s = s.replaceAll("..", "$0 ");
You may also want to trim the result to remove the extra space at the end.
See it working online: ideone.
Alternatively you can add a negative lookahead assertion to avoid adding the space at the end of the string:
s = s.replaceAll("..(?!$)", "$0 ");
//Where n = no of character after you want space
int n =2;
StringBuilder str = new StringBuilder("ABCDEFGHIJKLMNOP");
int idx = str.length() - n;
while (idx > 0){
str.insert(idx, " ");
idx = idx - n;
}
return str.toString();
Explanation, this code will add space from right to left:
str = "ABCDEFGH" int idx = total length - 2; //8-2=6
while (8>0)
{
str.insert(idx, " "); //this will insert space at 6th position
idx = idx - n; // then decrement 6-2=4 and run loop again
}
The final output will be
AB CD EF GH
I wrote a generic solution for this...
public static String insertCharacterForEveryNDistance(int distance, String original, char c){
StringBuilder sb = new StringBuilder();
char[] charArrayOfOriginal = original.toCharArray();
for(int ch = 0 ; ch < charArrayOfOriginal.length ; ch++){
if(ch % distance == 0)
sb.append(c).append(charArrayOfOriginal[ch]);
else
sb.append(charArrayOfOriginal[ch]);
}
return sb.toString();
}
Then call it like this...
String result = InsertSpaces.insertCharacterForEveryNDistance(2, "javastring", ' ');
System.out.println(result);

Categories