Given a string representing a simple arithmetic expression, solve it and return its integer value. The expression consists of two numbers with a + or – operator between the numbers, i.e., it will of the form x+y or x-y where x and y are not negative
MyApproach
I created the NewString and stored the first string till the operator does not come.I took the operator in the character position.I created the second string and stored the rest of the strings into the new String.I then converted them into numbers using parseInt.And then I added the numbers.
What I want to do 123+82=205
I am doing 123+43+82=248.I am not able to figure out how to position the character.
Can anyone guide me what I am doing wrong?
public int solve(String str)
{
String strnew1="";
String strnew2="";
int i=0;
char ch1=str.charAt(i);
while((ch1>=48)&&(ch1<=57))
{
strnew=strnew+ch1;
i++;
}
int p=str.charAt(i);
i++;
while((ch1>=48)&&(ch1<=57))
{
strnew2=strnew2+ch1;
i++;
if(i==str.length())
{
break;
}
}
int n1=Integer.parseInt(strnew1);
int n2=Integer.parseInt(strnew2);
n1=n1+p+n2;
return n1;
}
Test Case result.
Parameters Actual Output ExpectedOutput
123+82 248 205
Here is a nice way to accomplish your task. Basically, you iterate till you find the '+' r '-' sign and meanwhile append characters to a String. Now maintain a boolean value which tells you to add or subtract and set this value when you reach the sign. Now, iterate past the operator sign and append characters to another string. Finally, parse them into integers, add/subtract them and return the result.
public static int Solve(String input) //Assume input="100+50" for eg.
{
int cnt=0;
boolean op=false; //Default set to subtract
String raw_a="", raw_b="";
while(input.charAt(cnt)!='+')
raw_a+=input.charAt(cnt++); //The first part
if(input.charAt(cnt)=='+') //setting the operation
op=true;
cnt++;
while(cnt!=input.length())
raw_b+=input.charAt(cnt++); //the second part
int a=Integer.parseInt(raw_a), b=Integer.parseInt(raw_b); //parsing them
int ans =op? a+b: a-b; //If true then add else subtract
return ans; //Return the ans
}
You cannot use the operator like this.
Well, you add
int p=str.charAt(i);
if charAt(i) is a '+' symbol, you add additional 43 ('+' == ascii 43) by implicitly casting a char to int.
Better define 2 cases ('+' / '-') and use the operator:
if (p == 43) { //or p == '+'
return n1 + n2;
} else if (p == 45) { //or p == '-'
return n1 - n2
}
return -1; //undefined
What is the ASCII value of + -> 43.
What is the difference between 248 and 205, 43.
Got the mistake?
You are not actually adding those 2 numbers, you are adding those two numbers with the ASCII value of the operator.
What you should be doing is.
if(p == '+')//check if it is a addition
{
sum = n1 + n2;
}
else
sum = n1 - n2;
Related
Hi I am making a method that can take an integer as a parameter and compute how many zeros its binary form has. So for example, if I have binaryZeros(44), its binary form is 101100. Therefore, binaryZeros(44) should return 3. However, I am making some errors and I cannot tell where it is coming from. I would appreciate it if someone can point out where I am making that error, or if my approach (logic) to this problem is good enough. Thank you!
My code is Below:
public static int binaryZeros(int n) {
int zeroCount = 0;
double m = n;
while (m >= 0.0) {
m = m / 2.0;
if (m == Math.floor(m)) {
zeroCount++;
} else {
m = Math.floor(m);
}
}
return zeroCount;
}
Below is a more concise way to solve this problem
public static int binaryZeros(int n) {
int zeroCount = 0;
// Run a while loop until n is greater than or equals to 1
while(n >= 1)
{
/* Use modulo operator to get the reminder of division by 2 (reminder will be 1 or 0 as you are dividing by 2).
Keep in mind that binary representation is an array of these reminders until the number is equal to 1.
And once the number is equal to 1 the reminder is 1, so you can exit the loop there.*/
if(n % 2 == 0)
{
zeroCount++;
}
n = n / 2;
}
return zeroCount;
}
Your approach is good, but I think there's a better way to do it. The Integer class has a static method that returns the binary of a number: Integer.toBinaryString(num) . This will return a String.
Then, you can just check if there are any 0 in that string with method that has a for loop and evaluating with an if:
public int getZeros(String binaryString){
int zeros = 0;
for(int i=0; i < binaryString.length; i++)
if(binaryString.charAt[i].equals('0')
zeros++;
return zeros;
}
I believe this would be a simpler option and it doesn't have any errors.
Once m == 0.0, it will never change, so your while loop will never stop.
If you start with a number m >= 0, it can never become negative no matter how many times you divide it by 2 or use Math.floor. The loop should stop when m reaches 0, so change the condition to while (m > 0.0).
Note that you could do the same thing with built-in standard library methods. For example, there is a method that returns the number of leading zeros in a number, and a method that returns the number of bits set to 1. Using both you can compute the number of zeros that are not leading zeros:
static int binaryZeros(int n) {
return Integer.SIZE - Integer.numberOfLeadingZeros(n) - Integer.bitCount(n);
}
Here is one way. It simply complements the integer reversing 1's and 0's and then counts the 1 bits. You should not be using floating point math when doing this.
~ complements the bits
&1 masks the low order bit. Is either 1 or 0
>>> shifts right 1 bit including sign bit.
System.out.println(binaryZeros(44) + " (" +Integer.toBinaryString(44) +")");
System.out.println(binaryZeros(-44) + " ("Integer.toBinaryString(-44)+")");
public static int binaryZeros(int v) {
int count = 0;
while (v != 0) {
// count 1 bits
// of ~v
count += (~v)&1;
v >>>=1;
}
return count;
}
Prints
3 (101100)
4 (11111111111111111111111111010100)
Just be simple, whe there's Integer.bitCount(n) method:
public static int binaryZeros(int n) {
long val = n & 0xFFFFFFFFL;
int totalBits = (int)(Math.log(val) / Math.log(2) + 1);
int setBits = Long.bitCount(val);
return totalBits - setBits;
}
public static int getZeros(int num) {
String str= Integer.toBinaryString(num);
int count=0;
for(int i=0; i<str.length(); i++) {
if(str.charAt(i)=='0') count++;
}
return count;
}
The method toBinaryString() returns a string representation of the integer argument as an unsigned integer in base 2. It accepts an argument in Int data-type and returns the corresponding binary string.
Then the for loop counts the number of zeros in the String and returns it.
Write a method this passed two integers which returns true if the two numbers x and y have the same number in the ones place.
My Code:
int number;
while( number > 0) {
print (number%10);
number = number/10;
I know this is wrong but I am not sure where to start; I am a beginning coder.
What you can do is convert the integers to a String and get the character at the last index and see if they are equal.
public void lastDigitEqual(int a, int b){
String astring = Integer.toString(a);
String bstring = Integer.toString(b);
if(astring.charAt(astring.length()-1) == bstring.charAt(bstring.length()-1)){
System.out.println("True");
}else{
System.out.println("False");
}
}
Or another way of doing it is just getting the numbers mod 10. This will return the remainder of the two numbers when they are divided by 10, which will basically just be the ones digit. Then, you can check if they are equal.
public void lastDigitEqual(int a, int b){
int amod = a % 10;
int bmod = b % 10;
if(bmod == amod){
System.out.println("True");
}else{
System.out.println("False");
}
}
I tested both these ways and they work.
I'm trying the following: public static Element parse(String input) {
gets a String as an input and has to determine if the input either is a fraction or an operator.
This is one example:
sin(x) + (1/x) / x + 7
My code already checks if there is the same amount of opening and closing parenthesis, as well as if there always is a numerator and a denominator if there is a fraction submitted.
Now I've got a problems:
1. A new Fraction element should be created if there is a "/" present in the String that is not surrounded by parenthesis. In the example above, sin(x) + (1/x) would be the numerator and x + 7 would be the denominator. I don't really have any idea how to split the String according to this.
Final Output
Help would be appreciated.
Thanks!
First of all you should maybe put your String into a charArray which is easier to deal with at some point.
What I would do then is taking the charArray in a for loop which counts up or down based on the average lenght of your numberator and denominator. You count on the one hand the numbers of opened parenthesis and on the other hand you look for "/" and if parenthesis is 0 you count this as a numerator...
Ok now in Code.
public static Element parse(String s) {
// ...
char[] c = s.toCharArray();
int brackets = 0;
for (int i = 0; i < c.length(); i++) {
if (c[i] == '(') brackets++;
else if (c[i] == ')') brackets--;
else if (c[i] == '/' && brackets == 0) return new FractionElement();
}
// ...
return new OperatorElement();
}
Hope I was able to help you ;) Had a similar problem recently...
PS: If you want to split the numerator and the denominator into 2 substrings just do this:
//...
else if (c[i] == '/' && brackets == 0) {
String numerator = s.substring(0, i);
String denominator = s.substring(i+1, s.length);
}
//...
I'm new to Java and had a question about summing together the digits of a single binary value in Java.
For example,
If the binary value has an even number of 1's, I would like to output the String "even" to another method. If there are an odd number of 1's, then I want to output the String value "odd".
Below is an example of my code:
String eoro;
String name = "1010101011";
int num = Integer.parseInt(name, 2);
System.out.println(num);
if(num % 2 == 0)
eoro = "even";
else
eoro = "odd";
System.out.println(eoro);
The output comes up as
683
odd
I'm not sure if Integer.parseInt(name, 2); is the correct way of doing this, but I am unaware of another way of summing the digits of a single String value.
Please do not be rude and thanks for any help you can provide!
The shortest would be probably:
new BigInteger(value, 2).bitCount();
new BigInteger(value, 2) parses string as binary integer, bitCount() counts the bits. I'd use BigInteger as it is not clear, how long the string might be. You could use Integer or Long or other types if you're sure the string is short enough.
Alternatively you can just cound 1s in the string.
int result = 0;
for (char c: value.toCharArray()) {
result += c == '1' ? 1 : 0;
}
Integer.parseInt is definitely not the right method. It will parse the given string to an integer, but an integer being odd or even is unrelated to the number of "1"s. E.g., consider the following:
public static void main(String[] args) {
String eoro;
String name = "10";
int num = Integer.parseInt(name, 2);
System.out.println(num);
if(num % 2 == 0)
eoro = "even";
else
eoro = "odd";
System.out.println(eoro);
}
This will print
2
even
Which is not the output you want.
An easy way to count 1s in a string is to stream its characters and count them:
long numOnes = name.chars().filter(c -> c == '1').count();
public static void main(String[] args) {
// declare variables
String name = "1010101011";
String eoro = (name.chars().filter(c -> c == '1').count() % 2 == 0)?"even":"odd";
System.out.print(eoro);
}
If the binary value has an even number of 1's, I would like to output the String "even"
Just because a binary value has an even number of 1's doesn't mean the decimal representation of that number be an even value, or num % 2 == 0. For example, if you have a 1 as the least significant value, as you have here, this will always make the value odd.
You can count using a loop, or like this.
int ones = name.replace("0", "").length();
if (ones % 2 == 0)
System.out.println("even");
else
System.out.println("odd");
Refer: Java: How do I count the number of occurrences of a char in a String?
I need to write a Java program that prompts the user to enter an integer consisting of exactly 2 digits; then displays on the screen the sum of its individual digits.
I am stuck here. What am I doing wrong?
import java.util.Scanner ;
public class ss {
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
int x;
System.out.println("Please Enter a number consists of 2 digits only : ");
x = input.nextInt();
x.length() == 2;
}
}
and the last line contains an error!
Assuming that x is positive, a simple way to check if it has exactly two digits would be:
if (x >= 10 && x <= 99) {
// x contains exactly two digits
}
The variable x is of type int, so you can't call a method on it. You need to either read the input as a String or convert the int to a String then call length(), or just test that the int is between 10 and 99, inclusive.
In a programming langauge, there are things called L-values and R-values. In an assignment operation, a L-value can accept a R-value as input. This comes from the typical layout which has L-values on the left of the assignment operator and R-values on the right side of the assignment operator.
x = 5;
x is the L-value and 5 is the R-value. It is possible to assign five to x.
However, a function returns a R-value. Therefore, it is possible to do this
x = a.length();
but is is not possible to do
a.length() = x;
because you can not assign a value to the return of a function.
Fundamentally, L-values are names which represent a value, but R-values are values or items which when analyzed result in the return of values.
Now, if you used the equals comparison operator, both values must be R-values, because no assignment is being performed
a.length == x
is just fine, because it is not the assignment operator = but rather one of the comparison operators ==.
Your error comes because x is a primitive, not an object. Only objects have methods like length(). A quick an easy way to determine the length of an integer is by using Math.log().
public int length(int n){
if (n == 0) return 1; // because Math.log(0) is undefined
if (n < 0) n = -n; // because Math.log() doesn't work for negative numbers
return (int)(Math.log10(n)) + 1; //+1 because Math.log10 returns one less
//than wanted. Math.log10(10) == 1.
}
This method uses the fact that the base b logarithm of an integer a is related to the length of the integer a.
Or, if you don't know how to use methods, you could do this (assuming n is the integer to check):
int length = (n == 0)? 1: ((n > 0)? (int) (Math.log(n)) + 1: (int) (Math.log(-n)) + 1);
Or, if you don't use the ternary operator, you could expand it:
int length = -1; //placeholder; might not need it.
if (n == 0) length = 1;
else if (n > 0) length = (int) (Math.log(n)) + 1;
else length = (int) (Math.log(-n)) + 1;
You can't find the length of an int by calling a method on it, but you can find the length of a String.
Try converting the int to a String and finding the length of that:
boolean isTwoDigits = x.toString().length() == 2;
You cannot call length on integer just write
if(x>=10 && x<=99)
{
//write your code here
}