How can I tell that an integer is only 2 digits long? - java

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
}

Related

Digit amount in an integer [duplicate]

This question already has answers here:
Way to get number of digits in an int?
(29 answers)
Closed 24 days ago.
How can I find the amount of digits in an integer? Mathematically, and by using functions if there are any.
I don't really know how to do that, since I'm a somewhat beginner.
Another option would be to do it iteratively by dividing number by 10, until result is 0.
int number = ...;
int count = 1;
while ((number /= 10) != 0) {
count++;
}
In this program we use a for loop without any body.
On each iteration, the value of num is divided by 10 and count is incremented by 1.
The for loop exits when num != 0 is false, i.e. num = 0.
Since, for loop doesn't have a body, you can change it to a single statement in Java as such:
for(; num != 0; num/=10, ++count);
public class Main {
public static void main(String[] args) {
int count = 0, num = 123456;
for (; num != 0; num /= 10, ++count) {
}
System.out.println("Number of digits: " + count);
}
}
There are many ways to calculate the number of digits in a number. The main difference between them is how important performance is to you. The first way is to translate a number into a string and then take its length:
public static int countDigitsFoo(int x) {
if (x == Integer.MIN_VALUE) {
throw new RuntimeException("Cannot invert Integer.MIN_VALUE");
}
if (x < 0) {
return countDigitsFoo(-x); // + 1; if you want count '-'
}
return Integer.toString(x).length();
}
This method is bad for everyone, except that it is easy to write. Here there is an extra allocation of memory, namely the translation of a number into a string. That with private calls to this function will hit performance very hard.
The second way. You can use integer division and sort of go by the number from right to left:
public static int countDigitsBoo(int x) {
if (x == Integer.MIN_VALUE) {
throw new RuntimeException("Cannot invert Integer.MIN_VALUE");
}
if (x < 0) {
return countDigitsBoo(-x); // + 1; if you want count '-'
}
int count = 0;
while (x > 0) {
count++;
x /= 10;
}
return count;
}
but even this method can be improved. I will not write it in full, but I will give part of the code.
P.S. never use this method, it is rather another way to solve this problem, but no more
public static int countDigitsHoo(int x) {
if (x == Integer.MIN_VALUE) {
throw new RuntimeException("Cannot invert Integer.MIN_VALUE");
}
if (x < 0) {
return countDigitsHoo(-x); // + 1; if you want count '-'
}
if (x < 10) {
return 1;
}
if (x < 100) {
return 2;
}
if (x < 1000) {
return 3;
}
// ...
return 10;
}
You also need to decide what is the number of digits in the number. Should I count the minus sign along with this? Also, in addition, you need to add a condition on Integer.MIN_VALUE because
Integer.MIN_VALUE == -Integer.MIN_VALUE
This is due to the fact that taking a unary minus occurs by -x = ~x + 1 at the hardware level, which leads to "looping" on -Integer.MIN_VALUE
In Java, I would convert the integer to a string using the .toString() function and then use the string to determine the number of digits.
Integer digit = 10000;
Integer digitLength = abs(digit).toString().length();

How to calculate the number of zeros in binary?

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.

How to find sum of the digits of a binary value in a single string

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?

Output for Solving an expression does not come as expected

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;

decimal to binary conversion java

My method seems to only work for all int less than 2^10. If it is greater than or equal to this value then it just returns 2^32. I'm not sure how my program is even getting this. I need to make it work for all int less than or equal to 2^15. Can anybody at least see why it's returning 2^32 for int greater than or equal to 2^10? If so then let me know please.
public static int DecToBin(int num) {
int binNum = 0;
int divisor = num;
int mod = 0;
int exp =0;
while(divisor != 0){
mod = divisor%2;
divisor = divisor/2;
if(mod==1){
binNum = (int) (binNum + (Math.pow(10, exp)));
}
exp++;
}
return binNum;
}
An always easy way to accomplish this is:
Integer.toBinaryString(int);
This is the easiest way to do this but their might be more efficiant ways to do it.
Hopefully this is what you were looking for
As Taco pointed out, you can call Integer.toBinaryString(int), but if this is for an assignment or something where you should write the method yourself, here is what I would do.
I would write a method, that will constantly divide the number by 2, and store the remainders in a String. Something like this:
String binaryString = "";
int value = 100;
while(value > 0){
int remainder = value % 2;
value = value/2;
binaryString = remainder + binaryString;
}
I tested this in a quick console run and it produced '1100100' which is correct.
EDIT I used this as a reference.

Categories

Resources