Reputation: 407
During the method call compute(ee, temp1, s1, k)
from method smaller()
the argument value which am passing is not same as the one which am receiving, can someone help me with this issue?
*This is my problem statement-Get the least number after deleting k digits from the input number. For example, if the input number is 24635,the least number is 23 after deleting 3 digits.
I am expecting the final output to be 23 but getting infinite loop.
public class Delete3 {
public static void main(String[] args) {
int k = 3;
int num = 24635;
StringBuffer num1 =new StringBuffer(Integer.toString(num));
int temp = 0;
StringBuffer s = new StringBuffer(num1);
temp = Integer.parseInt(s.deleteCharAt(0).toString());
temp = compute(num1, temp, s, k);
System.out.println(temp);
}
static int compute(StringBuffer num2, int temp, StringBuffer s, int k) {
while (Integer.toString(temp).length() >= k) {
for (int i = 0; i < num2.length(); i++) {
StringBuffer s1 = new StringBuffer(num2);
String a = s1.deleteCharAt(i).toString();
int temp1 = Integer.parseInt(a);
if (temp > temp1) {
temp = Integer.parseInt(a);
}
}
StringBuffer ee = new StringBuffer(Integer.toString(temp));
if (ee.length() >= k) {
smaller(temp, k);
}
}
return temp;
}
static void smaller(int temp, int k) {
StringBuffer ee = new StringBuffer(Integer.toString(temp));
StringBuffer s1 = new StringBuffer(ee);
StringBuffer s2 = new StringBuffer(ee);
Integer temp1 = Integer.parseInt(s2.deleteCharAt(0).toString());
compute(ee, temp1, s1, k);
}
}
Upvotes: 2
Views: 114
Reputation: 2155
You can use simple code as below :
import java.util.Arrays;
public class Delete3 {
public static void main(String[] args) {
int num = 246235789;
int numDigitRequired = 2;
System.out.println(getLeastNum(num, numDigitRequired));
}
static int getLeastNum(int num, int numDigitRequired) {
char[] a = (num + "").toCharArray();
Arrays.sort(a);
StringBuffer s = new StringBuffer();
for (int i = 0; i < numDigitRequired; i++)
s.append(Character.getNumericValue(a[i]));
return Integer.parseInt(s.toString());
}
}
Upvotes: 0
Reputation: 1081
The infinite loop you are getting is because you are calling smaller()
from inside compute()
and compute()
from inside smaller()
. If this is done intentionally then also add a terminating condition , which would prevent it from looping infinitely.
Upvotes: 1