Search code examples
stringrecursionpython-3.8parenthesesfloating

Write a function read number(s, i) that takes a string s and an integer I, and returns a pair consisting of


Making a calculator In this problem, you have to write a function evaluation that takes a string representation of a simple mathematical expression, e.g. "(1+2)3", and evaluates it to obtain the resulting number. The input string may include any of the following: positive numbers, +, -, , /, (, ). e numbers may or may not contain a decimal part, e.g. the number 3 could be given as "3" or as "3.0" or with any number of zeroes. All expressions will be fully parenthesized, e.g. you will only be given "(1+(23))-4", not "1+23-4". Your implementation should return the correct result for any possible expression of this form. is a complex task that may require multiple helper functions. Here is one suggested 1 approach, though you may do it differently as long as it is correct:

  1. Write a function read number(s, i) that takes a string s and an integer I, and returns a pair consisting of (i) the number starting at the ith character of the string, and (ii) the index after the last character of the number. For example, read number("1+(2.4/3)",3) should return (2.4,6) because "2.4" is formed from characters 3 to 5 of the given string.

Solution

  • Iterate through all characters, and check conditions

    double d=0;
    int j=0;
    int di=-1;
    for(j=i;j<s.length();j++)
    {
    char c=s.charAt(j);
    if(c>='0'&&c<='9')
    {
    d=d*10+((int)(c-'0'));
    }
    else if(c=='.')
    di=j;
    else 
    break;
    }
    if(di>=0)
     d/=Math.pow(10,j-di);
    

    Here d is value and j is index.