Searching for a digit and delete it in my int variable - java

I want to search a digit in my int variable and delete it.
Here is little part of the code (not finished, because i'm still on the implementation). I noticed that there are many use cases. So do you know an easier way to delete the digit?
public int getStringtoIntForEthType(int OxAB){
String myInt = Integer.toString(OxAB);
if(Integer.toString(OxAB).contains("x")){
myInt = myInt.substring(2);
}
StringBuilder myIntBuilder = new StringBuilder(myInt);
for(int a = 0; a<=myInt.length();a++){
if(a-1 < 0 && myIntBuilder.charAt(0)!=0 && myIntBuilder.charAt(a)==0){
}
}
return Integer.parseInt(myIntBuilder.toString());
}

To delete all existence of that Digit from the number here is a function :-
public int DeleteDigit(int number, int numberToDel)
{
String Num = "" + number;
Num = Num.replace(numberToDel + "", "");
if(Num.length != 0)
return Integer.parseInt(Num);
return 0;
}
this would return an integer without the digit

Related

Count Words Using indexOf

I can't use arrays, only simple Java (if, for, while, substring, length, indexOf)
public int howManyWords(String s){
myString = "I have a dream";
int count = 1;
int length = 0;
while(count>=0){
count = myString.substring(String.valueOf(length),myString.indexOf(" "));
count++;
length = myString.indexOf(" ");
}
return count;
}
Should return 4
First of all, you made infinite loop, because count is 1, and you just increase it.
Second, you haven't even try to write this code in some IDE, because it would throw you a syntax error, because you are assigning string to int, when you do count = myString.substring()
So, instead of using count in loop, you can use myString.indexOf
something like this could work if you don't care what is going to happen with myString
int count = 0;
while(myString.indexOf(" ") >= 0) {
count++;
myString = myString.substring(myString.indexOf(" ") + 1)
}
return count;
Let's assume that the string you are testing does not contain leading or trailing spaces, because that affects the solution. The example string in your question does not contain leading or trailing spaces.
Simply call method indexOf(String, int) in a loop and in each iteration you set the int parameter to one more than what you got in the previous iteration. Once the value returned by method indexOf() is -1 (minus one), you are done. But don't forget to add the last word after you exit the loop.
String myString = "I have a dream";
int count = 0;
int index = 0;
while (index >= 0 && index < myString.length()) {
index = myString.indexOf(" ", index);
System.out.println("index = " + index);
if (index >= 0) {
index++;
count++;
}
}
if (index < 0) {
count++;
}
System.out.println("count = " + count);
Edited : Added missing else case.
Try the following code :
Remove the counted words from your string using the substring and indexOf, and increment the count in each iteration.
public int countWords(String s){
String myString = "I have a dream";
int count = 0;
int length = myString.length();
while(length>0){
if((myString.indexOf(" ")!=-1) && (myString.indexOf(" ")+1)<length){
myString = myString.subString(myString.indexOf(" ")+1);
count++;
length = myString.length();
}
else {
length = 0;
break;
}
}
return count;
}
PS: Conventionally, your method names should denote actions, hence I suggested it to be countWords instead of howManyWords.

Java get new number but ignore numbers in front of letters

I am trying to think of a way to resolve my problem. I didn't found the perfect solution I hope someone here can help me out.
So, I have an array of identifier numbers like:
...
3113,
3114,
3115 A1,
3115 A2,
3116
...
I want to return the next number available to insert.
Currently Im using this function but for some reason it dont work I think because it is reading the number 3115 A1 as 31151.
In this example I want to return 3117.
Here's the function in JAVA:
public String getNewNumber(){
int lastNumber = 1;
for(String number : listNumbers){
if(Integer.parseInt(number.replaceAll("[^\\d.]", "")) > lastNumber){
lastNumber = Integer.parseInt(number);
}
}
int newNumber = lastNumber + 1;
return newNumber + "";
}
Instead of replacing the letters you should extract the number with split, this removes a lot of possible bugs when the string changes. This requires the first number in the string to be the one you want to extract.
public String getNewNumber(String[] listNumbers) {
int lastNumber = 1;
for (String listNumber : listNumbers) {
String splitNumber = listNumber.split("\\D")[0];
int parsedNumber = Integer.parseInt(splitNumber);
if(parsedNumber > lastNumber) {
lastNumber = parsedNumber;
}
}
int newNumber = lastNumber + 1;
return String.valueOf(newNumber);
}
number.replaceAll("[^\\d.]", "")
It will replace all non-digit number from the string, so 3115 A1 becomes 31151. So instead of replacing all non digit character from input number, find first non-digit character and take substring.
String getNewNumber(String[] listNumbers) {
int lastNumber = 1;
for (String number : listNumbers) {
int index = firstNonDigitIndex(number);
int numberInt = Integer.parseInt(number.substring(0, index));
if (numberInt > lastNumber) {
lastNumber = numberInt;
}
}
int newNumber = lastNumber + 1;
return Integer.toString(newNumber);
}
/**
* Returns index of first non-digit char in string or str.length()
*/
int firstNonDigitIndex(String str) {
for (int i = 0; i < str.length(); i++) {
if (!Character.isDigit(str.charAt(i))) {
return i;
}
}
return str.length();
}
Also if your input listNumbers is sorted (it seems from your example), so you don't need to iterate all numbers, just parse the last number.

Repeatedly removing a substring from a string

Problem: Remove the substring t from a string s, repeatedly and print the number of steps involved to do the same.
Example: t = ab, s = aabb. In the first step, we check if t is contained within s. Here, t is contained in the middle i.e. a(ab)b. So, we will remove it and the resultant will be ab and increment the count value by 1. We again check if t is contained within s. Now, t is equal to s i.e. (ab). So, we remove that from s and increment the count. So, since t is no more contained in s, we stop and print the count value, which is 2 in this case.
I tried to solve this using recursion
static int maxMoves(String s, String t) {
if ( null == s || "" == s || null == t || "" == t){
return 0;
}
int i = s.indexOf(t);
if(i != -1) {
return maxMoves(s.substring(0, i)+ s.substring(i+t.length(), s.length()), t) + 1;
} else {
return 0;
}
}
But I am only passing 9/14 test cases. I also tried this,
static int maxMoves(String s, String t) {
int count = 0,i;
while(true)
{
if(s.contains(t))
{
i = s.indexOf(t);
s = s.substring(0,i) + s.substring(i + t.length());
}
else break;
++count;
}
return count;
}
But that also only passed 9/14 cases.
Could anyone help me figure out which cases I am not covering?
Simply you can use String::replaceFirst with a while loop for example:
String s = "aabb";
String t = "ab";
int count = 0;
while (s.contains(t)) {
s = s.replaceFirst(Pattern.quote(t), "");
count++;
}
System.out.println(count);
Use String#replace
String s = "aabb";
String oldstr = s;
String x = "ab";
while(s.contains(x)){
s = s.replace(x, "");
}
System.out.println((oldstr.length()-s.length())/x.length());
An easy and efficient way is to accumulate the string character-by-character in a StringBuilder; if at any time its buffer ends with the string you want to replace, remove it:
StringBuilder sb = new StringBuilder();
int c = 0;
for (int i = 0; i < s.length(); ++i) {
sb.append(s.charAt(i));
int last = sb.length()-t.length();
if (last >= 0 && sb.indexOf(t, last) == last) {
sb.setLength(last);
++c;
}
}
// c is now the number of times you removed t from s.

how can I check if a string is a floating point number?

In my program I'm going to store user input in an array then going to check each character to see if it's a digit or dot or E or negative sign after that I'll store it in to an array called temps.
Now I have problem in my fleating method () that don't how should I make my condition for the pattern of floating number digit-digit-dot-digit-digit (e.g 12.22)
I have my work here:
public void sorting(String data) {
String[] temps = new String[200];
int cpos = 0;
int tpos = 0;
Arrays.fill(temps, null);
if (str.isEmpty() == false) {
char char1 = str.charAt(cpos);
int i = 0;
while (i < str.length()) {
char1 = str.charAt(cpos);
char1 = str.charAt(tpos);
System.out.println("the current value is " + char1 + " ");
tpos++;
if (Character.isDigit(char1)) {
temps[cpos] = "Digit";
// System.out.println(" this number is digit");
cpos++;
} else if (char1 == 'e' || char1 == 'E') {
temps[cpos] = "s_notaion";
cpos++;
} else if (char1 == '-') {
temps[cpos] = "negative";
cpos++;
} else if (char1 == '.') {
temps[cpos] = ".";
cpos++;
}
i++;
}
}
}
here is the method for floating number
private static boolean floating(String [] data) {
int count =0;
boolean correct = false;
for (int i = 0; i < data.length; i++) {
if (data[i]== "Digit" )
&& data[i]=="." && data[i]"Digit"){
// here is the problem for the condition
}
}
return false;
}
If I understood correctly, the Data array has stuff like ["Digit","Digit",".","Digit"]
So you want the
private static boolean floating(String [] data) {
method to return true if the array only has "Digit" entries and exactly one "." entry? is that it?
If so:
boolean foundLeDigit = false;
for (int i = 0; i < data.length; i++) {
if (data[i].equals("Digit") == false && data[i].equals(".") == false {
//we found something other than a Digit or . it's not a float
return false;
}
if(data[i].equals(".")) {
if(foundLeDigit) { return false; //as we found 2 "." }
foundLeDigit = true
}
}
return foundLeDigit;
The easiest way to test if a String can represent a float is to try to parse it:
String testString = "1.2345";
double result;
try {
result = Double.parseDouble(testString);
System.out.println("Success!")
}
catch (NumberFormatException nfe) {
// wasn't a double, deal with the failure in whatever way you like
}
The questions lacks a bit of context, so for my answer I'm going to presume that this is homework requiring a manual solution, and that all floating point numbers are supposed to be accepted.
Your approach (while over-engineered) is half-right: you are reducing the input string into classes of characters - digit, sign, exponent marker. What is missing is that now you have to make sure that these character classes come in the right order.
Identify the various parts of float numbers (just look at 0, -1.0, 400E30, 42.1E-30) and you'll see that they come in a specific order, even if some are optional, and that each part imposes restrictions on what characters are allowed there. For example, if there is an 'E' in the number, it has to be followed by a number (with optional sign).
So as you step through the characters of the string, think about how you could keep track of where you are in the number, and base your character validation on that (this is the state machine #JonKiparsky was mentioning).
A few small things:
Don't compare strings with '==' - use equalsTo().
Think about what it means if sorting() finds a character which is neither a digit, a sign, or the exponent 'E'?
You allocate the temps array for 200 entries, but the input string could be larger.
using the regular expression is the best way to Handel this problem
private static boolean floating(String [] data) {
int count =0;
boolean correct = false;
for (int i = 0; i < data.length; i++) {
if (str.matches("((-|\\+)?[0-9]+(\\.[0-9]+)?)+")){
System.out.println(" it's a floating number ");
correct= true;
break;
}else
correct = false;
}if (correct ==true){
return true;
}else
return false;
}

Can anybody see why here the two "Integers" can't be compared?

public String minWindow(String S, String T) {
if (T.length() > S.length())
return "";
HashMap<Character, Integer> set = new HashMap<>();
for (int i = 0; i < T.length(); i++) {
if (!set.containsKey(T.charAt(i))) {
set.put(T.charAt(i), 1);
} else {
set.put(T.charAt(i), set.get(T.charAt(i)) + 1);
}
}
int count = 0;
int min = Integer.MAX_VALUE;
int begin = 0;
int end = 0;
LinkedList<Integer> index = new LinkedList<>();
HashMap<Character, Integer> record = new HashMap<>();
for (int i = 0; i < S.length(); i++) {
Character tmp = S.charAt(i);
if (set.containsKey(tmp)) {
index.add(i);
if (record.containsKey(tmp)) {
record.put(tmp, record.get(tmp) + 1);
} else {
record.put(tmp, 1);
}
int num1 = record.get(tmp);
int num2 = set.get(tmp);
if (num1 == num2) {
count++;
}
if (count == set.size()) {
Character head = S.charAt(index.peek());
while (record.get(head) > set.get(head)) {
record.put(head, record.get(head) - 1);
index.remove();
head = S.charAt(index.peek());
}
if (index.getLast() - index.peek() < min) {
min = index.getLast() - index.peek();
begin = index.peek();
end = index.getLast();
}
}
} else {
continue;
}
}
if (min == Integer.MAX_VALUE) {
return "";
} else {
return S.substring(begin, end + 1);
}
}
This is the my code of one Leetcode problem. But I don't think it involves the algorithm problem. So I post it here. Here it is the problem:
I use a hashmap "record" to record the duplicated characters in S and another one "set" to record the duplicated characters in T. When the number of the duplicated characters equal, plus one to variable "count";
I passed all the test except the last one S is a string of length 100000 and T is a string with length 10001.
I must use this form:
int num1 = record.get(tmp);
int num2 = set.get(tmp);
if (num1 == num2) {
count++;
}
instead of:
if(record.get(tmp)==set.get(tmp)){
count++;
}
Only like this can the two integers be compared or the "count" won't be plused. Why the first 265 test cases can pass but the last large string causes the problem? Thank you in advance.
Because the value of your Maps are Integer. Integer are objects and have to compared using the equals method.
if(record.get(tmp).equals(set.get(tmp))){
an it's an "autoboxing trap", you are putting Integer in record and set. If you call the get method you get two Integer thant must be compared with equals.
When you write
int num1 = record.get(tmp);
2 distinct operations happen
Retrieve the Integer
Convert the Integer to int (so you can use ==)
another trap is with null objects it the Integer is null
int num1 = record.get(tmp);
gives you a NullPointerException
It is returning Integer instead of int as you have HashMap<Character, Integer>, so it is not giving expected output for ==.
You can use
if(record.get(tmp).equals(set.get(tmp))){
You can look at this (difference between an int and an Integer) as well as this (Integer equals vs. ==) answer
Why the first 265 test cases can pass but the last large string causes the problem?
Answer: The JVM is caching Integer values. == only works for numbers between -128 and 127

Categories