I keep getting these errors when I run my program, can anyone spot the mistake? I am not experienced with using recursion and I might have messed up base case. My testing consists of two numbers of the same length, and my goal is to multiply two Big numbers without using the built in class. The method add just takes in two strings which are numbers and adds them, I checked and it works no matter how big the numbers are.
Error NumberFormatException: For input string: ""
Integer.parseInt(Integer.java:592)
public static String mu (String value1, String value2){
int length1 = value1.length();
int length2 = value2.length();
//If one value has more digits than the other, add zeroes to the front...
int temp1;
int temp2;
int multiply;
if (length1==1 || length2 ==1){
temp1 = Integer.parseInt(value1);
temp2 = Integer.parseInt(value2);
multiply = temp1*temp2;
return multiply +"" ;
}else if (length1 ==0 || length2 ==0){
return "";
}
int firstHalf = length1/2;
int secondHalf = length1 - firstHalf;
String value1First = value1.substring(0, firstHalf);
String value1Second = value1.substring(firstHalf, secondHalf);
String value2First = value2.substring(0, firstHalf);
String value2Second = value2.substring(firstHalf, secondHalf);
String ac = mu (value1First, value2First);
String ad = mu (value1First, value2Second);
String bc = mu(value1Second, value2First);
String bd = mu(value1Second, value2Second);
String zeroesToAdd= null;
String zeroesToAdd2 = null;
for (int i=0; i<length1; i++){
zeroesToAdd = "0"+ zeroesToAdd;
}
for (int i=0; i<length1/2; i++){
zeroesToAdd2 = "0"+ zeroesToAdd2;
}
String firstPart = ac + zeroesToAdd;
String secondPart = (add(ad,bc))+zeroesToAdd2;
String thirdPart = bd;
String add1 = add(firstPart, secondPart);
String add2;
return add(add1, thirdPart);
}
Error NumberFormatException: For input string: ""
Integer.parseInt(Integer.java:592)
is caused by the code
Integer.parseInt(value1) or
Integer.parseInt(value2)
You might want to try add more cases for combination of str lengths (1,1) (1,0) (0,1) (0,0). Following code might help!
if (length1==1 && length2 ==1){
temp1 = Integer.parseInt(value1);
temp2 = Integer.parseInt(value2);
multiply = temp1*temp2;
return multiply +"" ;
}else if (length1 ==0 && length2 ==0){
return "";
}
else if (length1 ==0 && length2 ==1){
return value2;
}
else if (length1 ==1 && length2 ==0){
return value1;
}
Hope it helps!
Related
I need to write a function when given a String of integers, it returns a String of integers where all consecutive integers are replaced with the sum of those integers.
For example:
When given: String = "144404331" the function returns "40461". You might think it would be "1120461" however we need to continue the process until there are no consecutive digits.
My solution to this is extremely long and was wondering if anyone had a recursive / intuitive solution that could be completed in a reasonable amount of time.
Method header:
String consecutiveSum(String number) {}
Yes, you can use recursive solution e.g. (c# code):
private static string consecutiveSum(string text)
{
StringBuilder sb = new StringBuilder(text.Length);
bool wantRecursiveCall = false;
char prior = '\0';
int sum = -1;
foreach (var c in text)
{
if (c != prior)
{
if (sum >= 0)
sb.Append(sum);
sum = 0;
}
else
wantRecursiveCall = true;
sum += c - '0';
prior = c;
}
sb.Append(sum);
return wantRecursiveCall ? consecutiveSum(sb.ToString()) : sb.ToString();
}
I am using a 2 linked list to represent 2 very long integers, each digit occupy one node. I need to compute for their gcf fast but my current algorithm computes for a very long time. Please help me improve it/or if you can suggest other faster algorithms for linked list.
here's my current code:
int findGCD(number **larger, number **small, number **gcdtop){
number *a = *larger, *b = *small, *aptr, *bptr;
printlist(larger);
printlist(small);
int equal = checkEqual(a, b); //traverse through linked list a & b and compare if equal, returns 1 if true
int large=0, borrow=0, adata=0, bdata=0, i=0;
while(equal!=1){
equal = checkEqual(a, b);
if(equal==1) break;
flip(&a); //Flips the linked list
flip(&b);
large = whatGreater(&a, &b); //Checks which linkedlist is greater
flip(&a); //Flip it back
flip(&b);
borrow=0;
//Do repeated subtraction (Euclid's algorithm)
if(large==1){
aptr = a;
bptr = b;
while(a && b){
adata = a->data;
bdata = b->data;
adata = adata - borrow;
if(adata>=bdata){
a->data = (adata-bdata);
borrow=0;
}
else if(adata<bdata){
adata = adata+10;
a->data = (adata-bdata);
borrow = 1;
}
a = a->next;
b = b->next;
}
a = aptr;
b = bptr;
}
else if(large==0){
aptr = a;
bptr = b;
while(a && b){
adata = a->data;
bdata = b->data;
bdata = bdata - borrow;
if(bdata>=adata){
b->data = (bdata-adata);
borrow=0;
}
else if(bdata<adata){
bdata = bdata+10;
b->data = (bdata-adata);
borrow = 1;
}
a = a->next;
b = b->next;
}
a = aptr;
b = bptr;
}
}
I believe doing this division/modulo would be faster but I cannot implement it in linked list.
Here's a sample input: 15424832369192002264032565635067237193339888184999832384884463019917546384661904, 65227
Thank you in advance.
I am doing a problem from this blog
One day, Jamie noticed that many English words only use the letters A and B. Examples of such words include "AB" (short for abdominal), "BAA" (the noise a sheep makes), "AA" (a type of lava), and "ABBA" (a Swedish pop sensation).
Inspired by this observation, Jamie created a simple game. You are given two Strings: initial and target. The goal of the game is to find a sequence of valid moves that will change initial into target. There are two types of valid moves:
Add the letter A to the end of the string.
Reverse the string and then add the letter B to the end of the string.
Return "Possible" (quotes for clarity) if there is a sequence of valid moves that will change initial into target. Otherwise, return "Impossible".
My Questions:
My solution follows example steps: Firstly, reverse and append 'B', then append 'A'. I have no idea whether I need to use another order of the step(firstly, append 'A', then reverse and append 'B') at same time.
I got "ABBA" which should return "Possible", but "Impossible" was returned.
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println(canContain("B","ABBA"));
}
public static String canContain(String Initial, String Target){
char[] target = new char[1000];
char[] initial1 = new char[1000];
int flag = 0;
boolean possible = false;
int InitialLength = Initial.length();
int TargetLength = Target.length();
System.out.println("Initial:");
int countInitial = -1;
for(char x : Initial.toCharArray()){
countInitial++;
if(x=='A')initial1[countInitial]='A';
if(x=='B')initial1[countInitial]='B';
System.out.print(x+"->"+initial1[countInitial]+" ");
}
int countTarget = -1;
System.out.println("\nTarget:");
for(char y : Target.toCharArray()){
countTarget++;
if(y=='A')target[countTarget]='A';
if(y=='B')target[countTarget]='B';
System.out.print(y+"->"+target[countTarget]+" ");
}
System.out.print("\n");
//Check Initial char[]
System.out.print("---------------");
System.out.print("\n");
for(int t1 = 0; t1 <= countInitial; t1++){
System.out.print(initial1[t1]+"-");
}
System.out.print("\n");
for(int t3 = 0; t3 <= countTarget; t3++){
System.out.print(target[t3]+"-");
}
while(countInitial != countTarget){
if(flag == 0 && Initial != Target){
System.out.println("\n_______A_______");
countInitial++;
System.out.println("countInitial = "+countInitial);
initial1[countInitial] = 'A';
System.out.println(initial1[countInitial]);
for(int t1 = 0; t1 <= countInitial; t1++){
System.out.print(initial1[t1]+"-");
}
flag = 1;
}else if(flag == 1 && Initial != Target){
System.out.println("\n_______R_+_B_______");
int ct = 0;
char[] temp = new char[1000];
for(int i = countInitial; i >= 0; i--){
System.out.println("countInitial = "+countInitial);
temp[ct] = initial1[i];
System.out.println("ct = "+ct);
ct++;
}
initial1 = temp;
countInitial++;
initial1[countInitial] = 'B';
for(int t1 = 0; t1 < countInitial; t1++){
System.out.print(initial1[t1]+"-");
}
flag = 0;
}
}
if(initial1.equals(target)){
return "Possible";
}else{
return "Impossible";
}
}
Your immediate problem is that you apply rules in the particular order. However it is not forbidden to use the same rule multiple times in a row. So to get the target string from the initial you need to inspect all possible sequences of rule applications. This is known as combinatorial explosion.
Problems like this is usually easier to solve working backwards. If the target string is xyzA it may only be obtained by rule 1 from xyz. If the target string is xyzB it may only be obtained by rule 2 from zyx. So in pseudocode,
while length(target) > length(initial)
remove the last letter from target
if removed letter is "B"
reverse target
if target == initial
print "Possible"
else
print "Impossible"
Of course, reversal doesn't have to be explicit.
Here's a solution which will run for a linear time O(n). The idea is that you start from the target string and try to revert the operations until you reach a string with the same length as the initial string. Then you compare these 2 strings. Here's the solution:
private static final char A = 'A';
private static final String POSSIBLE = "Possible";
private static final String IMPOSSIBLE = "Impossible";
public String canObtain(String initial, String target) {
if (initial == null ||
initial.trim().length() < 1 ||
initial.trim().length() > 999) {
return IMPOSSIBLE;
}
if (target == null ||
target.trim().length() < 2 ||
target.trim().length() > 1000) {
return IMPOSSIBLE;
}
return isPossible(initial, target) ? POSSIBLE : IMPOSSIBLE;
}
private boolean isPossible(String initial, String target) {
final StringBuilder sb = new StringBuilder(target);
while (initial.length() != sb.length()) {
char targetLastChar = sb.charAt(sb.length() - 1);
if (targetLastChar == A) {
unApplyA(sb);
} else {
unApplyRevB(sb);
}
}
return initial.equals(sb.toString());
}
private void unApplyA(StringBuilder sb) {
sb.deleteCharAt(sb.length() - 1);
}
private void unApplyRevB(StringBuilder sb) {
sb.deleteCharAt(sb.length() - 1);
sb.reverse();
}
A little late to the party but this is a concise solution in Python that runs in linear time:
class ABBA:
def canObtain(self, initial, target):
if initial == target:
return 'Possible'
if len(initial) == len(target):
return 'Impossible'
if target[-1] == 'A':
return self.canObtain(initial, target[:-1])
if target[-1] == 'B':
return self.canObtain(initial, target[:-1][::-1])
I am making a password generator wich needs to make a string of upper and lower case letters givin in a random order. The max and min value is specified by two sliders.
I would like to give up two ranges (65, 90) and (97, 122) for the int variable that returns the number for the charachter, instead of using two variables with a different range.
When I use the range of (65, 122) there are characters being given that I don't want, when generating the password.
private void btnPaswoord_Click(object sender, RoutedEventArgs e)
{
GenereerPaswoord();
}
private void GenereerPaswoord()
{
int iMin = Convert.ToInt32(sldMin.Value);
int iMax = Convert.ToInt32(sldMax.Value);
txtPasw.Text = GeefPaswoord(iMin, iMax );
}
private string GeefPaswoord(int iMin, int iMax)
{
string sPaswoord ="";
if (sldMin.Value <= sldMax.Value)
{
int iLengtePaswoord = moWillekeurig.Next(iMin, iMax + 1);
for (int iTeller = 0; iTeller < iLengtePaswoord; iTeller ++ )
{
int iAsciiWaarde = moWillekeurig.Next(65, 123);
char cLetter = (char)iAsciiWaarde;
sPaswoord = sPaswoord + cLetter;
}
}
else
{
sldMin.Value = sldMax.Value;
}
return sPaswoord;
}
In this case the ranges are tiny, so you can generate an array of characters that contains all valid characters you might want to use in passwords and just draw from there:
var passwordChars =
Enumerable.Range(65, 26)
.Concat(Enumerable.Range(90, 26))
.Select(Convert.ToChar).ToArray();;
var password = new string(
Enumerable.Range(1, iLengtePaswoord)
.Select(_ => moWillekeurig.Next(passwordChars.Length))
.Select(x => passwordChars[x]));
To precisely answer your question, though, you can use so-called rejection sampling. That is, you draw random numbers until you get one that satisfies your criteria:
int iAsciiWaarde;
do
{
iAsciiWaarde = moWillekeurig.Next(65, 123);
} while (iAsciiWaarde <= 90 || iAsciiWaarde >= 96);
Input: "My Name is Pritam"
Output: "Pritam is Name My"
I have written this so far, but I'm bit confused with time complexity
public string ReverseWordsInAString(string str)
{
char[] temp = str.ToCharArray();
int startIndex = 0;
int endIndex = str.Length - 1;
temp = ReverseString(temp, startIndex, endIndex);
endIndex = 0;
foreach (char c in temp)
{
if(c == ' ')
{
temp = ReverseString(temp, startIndex, endIndex-1);
startIndex = endIndex + 1;
}
if (endIndex == str.Length-1)
{
temp = ReverseString(temp, startIndex, endIndex);
}
endIndex++;
}
str = new string(temp);
return str;
}
public char[] ReverseString(char[] chr, int start, int end)
{
while (start < end)
{
char temp = chr[start];
chr[start] = chr[end];
chr[end] = temp;
start++;
end--;
}
return chr;
}
When I call ReverseString method from a for loop I think it no more a O(n) solution. Please correct me if I'm wrong. Does anyone have any better solution.
in Java
String str= "My Name is Pritam";
String arr[] = str.split(" ");
for(int i = arr.length-1 ; i >=0 ; i--){
System.out.println(arr[i]);
}
Your code is O(n). You can see this by looking at the number of swaps each element is involved in, which is 2 (once for the initial reverse of the entire string, second for the word-wise reversal). In addition the foreach loop iterates over each element exactly once.
In Ruby:
sentence = "My name is Pritam"
print sentence.split(" ").reverse.join(" ")
In C;
char *s = "My Name is Pritam", *t = s + strlen(s), *end = strchr(s,' ')-1;
while( t != end )
{
*(t = strrchr(t,' ')) = '\0';
printf( "%s ", --t+2 );
}
printf( "%s", s );
Possible duplicate, I had asked a similar question some time back. But the responses I received were very interesting, actually it did change the way complexity should be thought about ;).... Time Complexity
Split the string and push it to a stack . Pop elements from stack and add it to a new string. Requires extra space,but just posted because it could be a easy way to implement string reverse
public class StringReverse {
public static void main (String args[]){
String input = "My name is Pritam";
Stack<String> stack = new Stack<String>();
String[] strings= input.split(" ");
for(String str :strings){
stack.push(str);
}
String reverse = "" ;
while(!stack.isEmpty()){
reverse = reverse + " " + stack.pop();
}
System.out.println(reverse);
}
}
in Python,
sentence = "My name is Pritam"
' '.join(sentence.split(" ")[::-1])