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.
Related
My code keeps printing out "true" no matter what I enter. My code does not show any errors, I enter 56 as the input and it still prints "true." I'm having a really hard time figuring out why. Also, I'm new to Java as well as Stack Overflow. Any help would be appreciated.
//Palindrome verification
temp = integer;
while (integer > 0)
{
remainder = integer%10;
reverse = reverse * 10 + remainder;
integer=integer /10;
}
if (integer==reverse)
System.out.println("True");
else
System.out.println("False");
In your program when while loop completely execute integer variable value will become zero and it is the problem.
you need to change if (integer==reverse) to if (temp==reverse).
complete code:
public class palindrom {
public static void main(String[] args) {
int integer = 122; //change this value according to your preference
int temp = integer;
int remainder;
int reverse = 0;
while (integer > 0){
remainder = integer%10;
reverse = reverse * 10 + remainder;
integer=integer /10;
}
if (temp==reverse)
System.out.println("True");
else
System.out.println("False");
}
}
You need compare START value with REVERSE. In your code (integer==reverse) will always be FALSE, because integer==0 after cycle in while.
int integer = 12344321;
int remainder, reverse = 0;
int start = integer;
while (integer > 0)
{
remainder = integer%10;
reverse = reverse * 10 + remainder;
integer = integer / 10;
}
if (start==reverse)
System.out.println("True");
else
System.out.println("False");
System.out.println(reverse);
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;
I need to write a method for comparing two binary numbers. I am storing the binary numbers in character arrays, so I can store big numbers (I can't use the BigInteger class or any other packages).
Example to make things clear:
char[] num1 = {'1','1','0'}
char[] num2 = {'1','1','1'}
I need to return 0 if they are equal, -1 if a < b and 1 if a > b
This is the approach I took:
static int compare(char[]a, char[]b) {
//If arrays lengths aren't equal I already know, one is bigger then the other
int a_len = a.length;
int b_len = b.length;
int a_bits = 0;
int b_bits = 0;
if (a_len > b_len)
return 1;
if (b_len > a_len)
return -1;
//I count the number of bits that are 1 in both arrays
for (int i = 0; i < a.length; i++) {
if (a[i] == '1') a_bits++;
if (b[i] == '1') b_bits++;
}
if(a_bits>b_bits)
return 1;
if(b_bits>a_bits)
return -1;
return 0;
}
So as far as I understand, this works in every case, but the case where the number of bits are equal (1100 is bigger than 1001 for example).
I was thinking I could add up the indexes in the for loop for each array and work from there, but I started thinking I may be overcomplicating things. Is this even a good approach to it? I'm starting to doubt it. Any insight is appreciated
I would look for the first index that is 1 in one of the numbers but 0 in the other number. You can replace the bit counting loop(keeping the length check) with:
for (int i = 0; i < a.length; i++) {
if (a[i] == '1' && b[i] == '0') return 1;
if (b[i] == '1' && a[i] == '0') return -1;
}
return 0;
Using some conversion and the binary parseInt offered by class Integer you can do this simple comparison regardless of the arrays' size. (I'd be careful instead with checking the length of the arrays because if you have leading zeros in one array this could bring some comparisons to miss).
String first = new String(a);
String second = new String(b);
int firstint = Integer.parseInt(first, 2);
int secondint = Integer.parseInt(second, 2);
if(firstint > secondint)
return 1;
if(firstint < secondint)
return -1;
return 0;
An alternative approach would be as follows:
Convert Array Of Characters into String.
Convert the resulting String into int.
Work out the logic from the resulting int
It will always work and you can print out the resulting conversion.
Hope this helps.
public static void main(String[] args) {
char[] num1 = {'1','1','0'};
char[] num2 = {'1','1','1'};
System.out.println(compare(num1, num2));
}
public static int compare(char[]num1, char[]num2) {
// Convert Array of Characters to String
String one = String.valueOf(num1);
String two = String.valueOf(num2);
// Convert to Integer (Binary to Decimal Conversion to base2)
int a = Integer.parseInt(one,2);
int b = Integer.parseInt(two,2);
int result = 0; // return result as equals i.e. 0.
if(a > b) { // Yes. Curly brackets are important in Java
result = 1;
} else if(a < b){
result = -1;
}
return result; // Use only one return, i.e. a variable.
}
Can anyone please learn me how to change this number 5486 to 4568 ? I need to change two pairs of numbers places. Any ideas please?
My code :
public Number shiftRight(int n) {
int length = (getNumOfDigits()+MINUSONE);
length = (int) Math.pow(TEN, length);
for (int i=0; i<n; i++){
int m=num%TEN;
num=(m*length) + (num/TEN);
}
return new Number(num);
}
public int shiftRightDistance(Number other){
int max = getNumOfDigits();
for (int i=0;i<max;i++)
{
if(compareTo(shiftRight(i))==ZERO)
{
return i;
}
}
return MINUSONE;
}
public Number swapPairs() {
}
}
The simplest (and least confusing) thing might be to convert the number to a char array, swap pairs of characters, and then convert back to a number. You can use String.valueOf(int), String.toCharArray(), new String(char[]) and Integer.valueOf(String) to put that together.
Alternatively, you can build on the following method that swaps the digits of a non-negative number less than 100:
private int swapDigitsLessThan100(int n) {
return 10 * (n % 10) + n / 10;
}
The way to build on that would be to extract every pair of digits from the original number, working recursively. The following deals with numbers that are an even number of digits long:
public int swapDigits(int n) {
if (n == 0) {
return 0;
return 100 * swapDigits(n / 100) + swapDigitsLessThan100(n % 100);
}
With this code, if n is an odd number of digits, the result will be to use a leading 0 as an additional digit.
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
}