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);
Related
I am trying Leetcode Question - 69. Sqrt(x)
Given a non-negative integer x, compute and return the square root of x.
Since the return type is an integer, the decimal digits are truncated, and only the integer part of the result is returned.
Note: You are not allowed to use any built-in exponent function or operator, such as pow(x, 0.5) or x ** 0.5.
class Solution {
public int mySqrt(int x) {
int ans = 0;
int i=1;
while(i*i<=x){
ans = i;
i++;
}
return ans;
}
}
This is the code I came up with. But the testcase input=2147395600 is not passing.
My Output = 289398
Expected Output = 46340
I'm confused as I have put the condition i*i<=x, then how can ans be more than the sqrt value?
Since you are comparing i * i with the input x, if the input x is too close to Integer.MAX_VALUE (2.147.483.647), like in that test case, i * i will be bigger than the maximum value allowed for an int to have and i*i<=x will be true.
Possible solutions:
Implement a binary search algorithm where max would be the floor(sqrt(Integer.MAX_VALUE)) or 46340.
Implement a algorithm where ans, i and x are declared locally as long type variables and in the return line you return the value cast to int using return (int)ans;
By running the following algorithm you can see the limit of a java int exploding and what happens afterwards.
int x = 2;
while(true) {
System.out.println(x);
x *= 2;
}
Not pretending to be fast, just the idea that (n+1)2=n2 + 2n + 1:
public static int mySqrt(int x) {
int i = 0;
while (x >= 0) {
x -= (i++ << 1) + 1;
}
return i - 1;
}
My JavaScript Solution
var mySqrt = function(x) {
var ans = 1;
if(x === 0){
ans = 0;
} else {
for (let i = 1; i< x;i++){
if(i*i === x){
ans = i;
break;
}
if(i*i >x){
ans = i - 1;
break;
}
}
}
return ans;
};
I want to round down an int in Java, what i mean is, if I have an int 45678, i want to convert that int into 40000
this is how im calling it
int den = placeValue(startCode,length);
and this is the code
static int placeValue(int N, int num)
{
int total = 1, value = 0, rem = 0;
while (true) {
rem = N % 10;
N = N / 10;
if (rem == num) {
value = total * rem;
break;
}
total = total * 10;
}
return value;
}
so if i have 89765, i would want 80000,
but instead it return the place value of whatever length is.
So,
for 89765, the length would be 5, so the return value is 5 i.e. the value in the ones place.
but if the number was 85760
then it would return 5000.
I hope that makes sense.
Any suggestions would be much appreicated.
In my opinions, if I can avoid 'calculating' I will compute the answer from other concept since I am not confidence on my math (haha).
Here is my answer. (only work in positive numbers)
I think the length of the inputted number is not necessary.
static int placeValue2(int N) {
String tar = N+"";
String rtn = tar.substring(0,1); // take first digital
for (int i=0;i<tar.length()-1;i++) // pad following digitals
rtn+="0";
return Integer.parseInt(rtn);
}
I appreciate you asked the question here.
Here is my solution. I don't know why you are taking two parameters, but I tried it from one param.
class PlaceValue{
int placeValue(int num){
int length = 0; int temp2=1;
boolean result=false;
long temp1=1;
if (num<0){
result=true;
num=num*(-1);
}
if (num==0){
System.out.println("Value 0 not allowed");
return 0;
}
while (temp1 <= num){ //This loop checks for the length, multiplying temp1 with 10
//untill its <= number. length++ counts the length.
length++;
temp1*=10;
}
for (int i=1; i<length; i++){//this loop multiplies temp2 with 10 length number times.
// like if length 2 then 100. if 5 then 10000
temp2=temp2*10;
}
temp2=(num/temp2)*temp2;
/* Let's say number is 2345. This would divide it over 1000, giving us 2;
in the same line multiplying it with the temp2 which is same 1000 resulting 2000.
now 2345 became 2000;
*/
if (result==true){
temp2=temp2*(-1);
}
return temp2;
}
}
Here is the code above. You can try this. If you are dealing with the long numbers, go for long in function type as well as the variable being returned and in the main function. I hope you understand. otherwise, ask me.
Do you want something like this?
public static int roundDown(int number, int magnitude) {
int mag = (int) Math.pow(10, magnitude);
return (number / mag) * mag;
}
roundDown(53278,4) -> 50000
roundDown(46287,3) -> 46000
roundDown(65478,2) -> 65400
roundDown(43298,1) -> 43290
roundDown(43278,0) -> 43278
So the equivalent that will only use the most significant digit is:
public static int roundDown(int number) {
int zeros = (int) Math.log10(number);
int mag = (int) Math.pow(10, zeros);
return (number / mag) * mag;
}
public class NumberPalindrome {
public static boolean isPalindrome(int number) {
int reverse = 0;
if (number<0){
number=number* -1;
}
while (number > 0) {
int lastDig = number % 10;
reverse = lastDig + reverse;
if (number<10) {break;}
reverse = reverse * 10 ;
number/=10;
}
if (number==reverse) {
return true;
}
return false;
}
}
why does my code not return true when I enter a palindrome number? I tried using it to print out the reverse value and it does it quite well, but just does not seem to get the boolean value straight though.
The problem was modifying the number variable, but then comparing it with the new generated reverse variable as if it was never edited.
Also, you were adding the last digit to the reverse variable before multiplying it by ten.
See the following code in Java:
public static boolean isPalindrome(int number) {
int reverse = 0;
if(number < 0) {
number *= -1;
}
int initialNumber = number;
while(number > 0) {
int lastDigit = number % 10;
reverse = (reverse * 10) + lastDigit;
if(number < 10) {
break;
}
number /= 10;
}
return initialNumber == reverse;
}
There are a few problems here. You need to save the original number for comparison with the the reversed number. The break statement confuses the logic.
To figure this out, I added some print statements to trace the progress. Adding print statements isn't elegant, but it is very useful.
Here is my version, with comments indicating what I changed.
public static boolean isPalindrome (int original)
{
// Need to save the original number for comparison
int number = original;
int reverse = 0;
if (number < 0)
{
number = number * -1;
}
while (number > 0)
{
int lastDig = number % 10;
// Update and shift reverse in one step
reverse = lastDig + reverse * 10;
number /= 10;
// Don't need extra break to terminate the loop
System.out.printf ("Check %d ; Reverse %d%n", number, reverse);
}
System.out.printf ("Final %d ; Reverse %d%n", number, reverse);
// Compare to original and return boolean value directly
return (original == reverse);
}
I need to write a program to receive a number from the user, use a user=defined method to reverse the number, then return the number as an integer. Below is what I have so far. I am trying to see if I can take each individual digit from the array and somehow put them together as an integer. Do I need to put them together as a string and then convert it to integer? or is there a simpler way all together to do this?
import java.util.*;
public class UserDefinedMethods
{
static Scanner keyboard = new Scanner(System.in);
public static int reverseDigits(int num)
{
int reverse[];
int i = 0;
int out = 0;
do
{
if (num < 0)
num = (num * -1);
reverse[i] = num % 10;
num = num/10;
i++;
}
while (num > 0);
out =
return reverse; //HERE IS MY PROBLEM I BELEIVE.
}
public static void main(String[] args)
{
int number = 0;
int output = 0;
System.out.println("Please enter a number:");
number = keyboard.nextInt();
output = reverseDigits(number);
System.out.println(output);
}
}
Reversing an int can be done as follows:
Set result to zero.
If the number is zero, return the result that you have so far
Add a trailing zero to the result
Replace trailing zero with the last digit of the original number
Drop the last digit of the original number
Go to step 2.
Here is how to do selected things in Java:
To get the last digit use int lastDigit = number % 10;
To drop the last digit use number /= 10;
To add zero as the last digit of the result use result *= 10;
To replace the trailing last digit use result += lastDigit;
Demo.
Ok first off, you're attempting to return the array reverse, but your method declaration is set to return an int (not int[]). Secondly, your code can be simplified as follows:
public static int reverseDigits(int num){
int reverse = 0;
while(num != 0){
reverse *= 10;
reverse += (num % 10);
num /= 10;
}
return reverse;
}
Hope this helps! :)
This question already has answers here:
How do I check if a number is a palindrome?
(53 answers)
Closed 9 years ago.
I need help with a method to check if a number is symmetric, so from what I understand I need to check equality between all the numbers and to make sure there is no different number amounts them...right?
This is my code:
public boolean isSemetric (int number) {
int temp;
boolean answer = true;
while (number != 0) {
temp = number % 10;
number /= 10;
if (temp != (number%10)) {
answer = false;
} else {
answer = true;
}
}
return answer;
}
I'm kind of new to programming so be forgiven to my code :/
Thanks!
As peter.petrov pointed out in the comment section of your question, your method as it's written will always return false, except for when number is equal to 0. The reason for this can be seen when you pass in a number like 111 and step through the code in a debugger. The final iteration will fail because number /= 10 will result in 0, and temp will be 1, which fails your test.
If you are indeed looking to identify palindromes, consider the following approach that should be simple to implement
1. copy number into temp
2. convert temp to a String, and reverse it (tmpStr)
3. convert tmpStr back to an integer (reversedInt)
4. compare number and reversedInt for equality
viola. Not the most efficient algorithm, but its easy to understand and gets the job done.
I would do it like this (I don't want to use String here and I don't want to use local array variable for the digits).
public static boolean isSymmetric (long number) {
if (number == 0) return true;
else if (number < 0) return false;
long DEG_10 = (long)(Math.pow(10, (int)Math.log10(number)));
while (number > 0){
long dStart = number / DEG_10;
long dEnd = number % 10;
if (dStart != dEnd) return false;
number = (number - dStart * DEG_10 - dEnd) / 10;
DEG_10 /= 100;
}
return true;
}
This is the easiest approach I can think of - Get the String value of the number, if the reverse is the same then it is symmetrical.
// Symmetry
public static boolean isSymmetric(int number) {
String val = String.valueOf(number); // Get the string.
StringBuilder sb = new StringBuilder(val);
return (val.equals(sb.reverse().toString())); // if the reverse is the same...
}
Here's a somewhat fixed up version of your code. However, it checks if all numbers are the same, e.g. 5555 or 111. 11211 would return false.
public boolean areAllDigitsTheSame (int number) {
int temp;
boolean answer = true;
while (number >= 10) {
temp = number % 10;
number /= 10;
if (temp != (number%10)) {
return false
}
}
return true;
}
Edit: The C++ answer in the linked question works by constructing the reverse number gradually in the loop, and finally checking if they're the same. This is a similar to what you are doing.
Here's another version for fun:
public boolean isPalindrome (int number) {
int reversedNumber = 0;
while (number > 0) {
int digit = number % 10;
reversedNumber = reversedNumber*10 + digit;
if (reversedNumber == number) { // odd number of digits
return true;
}
number /= 10;
if (reversedNumber == number) { // even number of digits
return true;
}
}
return false;
}