This question already has answers here:
Java reverse an int value without using array
(33 answers)
Closed 7 years ago.
Below is a code that I have for flipping a given integer and displaying the flipped results. It runs but I have issues for when the number is smaller than two digits. It obviously cannot be flipped. I wanted to make the loop an if else stating "if number is two digits or more reverse." "Else state that the integer needs to be two or more digits." how could I go about this?
import java.util.Scanner;
public class ReverseInteger {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter an integer that you would like to have reversed: ");
int number = input.nextInt();
reverse(number);
}
public static void reverse(int userInteger)
{
int tempDigit = 0;
while (userInteger > 0){
tempDigit = userInteger % 10;
System.out.print(tempDigit);
userInteger = userInteger / 10;
}
}
}
I am trying to get it to understand that 01 can be converted to 10. This would need to be done by the code understanding that the userInteger is more than one digit but I cant seem to figure out how to do that... Any ideas on how I can get this to check for two digits and execute the loop accordingly would be appreciated!
public static void reverse(int n)
{
int temp = 0;
int count = 0;
while(n != 0)
{
if(n%10 == 0)count++;
temp = temp*10 + n %10;
n /= 10;
}
for(int i = 0; i < count; i++)
{
System.out.print(0);
}
System.out.println(temp);
}
Convert the int to a String using Integer.toString method and save it to a string. Declare a String that will be later used as output. Start a for loop that goes through the number ( which was converted to a String) from its end to its beginning. It add each character from end to start to the output String. This results in the output String to be the reverse of the number String. Then just simply convert the output String using Integer.parseInt method and return the int value.
The code should look like:
public static int reverse(int n)
{
String number = Integer.toString(n);
String output;
for(int i = number.length()-1; i >= 0; i--)
output += number.charAt(i);
return Integer.parseInt(output);
}
I recommend using String.valueof(int).toCharArray(); and looping through in reverse to compose a new char[]. Then use Integer.parseInt(String);
Related
I am a beginner in Java and trying to learn. I have an integer from whom I want to calculate the double of each digit and then restore the answer in the integer. I think that I have to use the for() loop and tempvalue. I have the number 1234 and I need to get 2468.
I did this and I got 1234. Can someone find the issue, I am not very good with the index concept.
public class Doublevalue {
public static void main(String[] args) {
num=1234;
for(int i=0;num<0;i++) {
int tempvalue=(num%10*2)/10;
num=tempvalue;
System.out.print(num);
}}}
Because doubling digits is only valid when every digit is less than 5, the solution can be just
num *= 2;
But if you want the treat each digit separately, you need to do something like this:
int tmp = 0;
for (int column = 1; num > 0; column *= 10) {
tmp += (num % 10) * column * 2;
num /= 10;
}
num = tmp;
See live demo.
You can do an in-place replacement of each digit, but the logic is a little more complicated.
The code you currently provided has everything right - except for what you are doing in the loop.
In your example, you are executing int tempvalue=(num%10*2)/10;. I'm pretty certain that you are not sure what you are doing. What the line is doing is getting the remainder of the number when it is divided by 10, multiplying it by 2, then dividing by then. I can't seem to understand why you are doing this, so I will provide my own solution.
public class DoubleDigits {
public static void main(String[] args) {
DoubleDigits dd = new DoubleDigits();
System.out.println(dd.doubleDigits(1234));
}
public int doubleDigits(int number) {
StringBuilder str = new StringBuilder();
String testCase = String.valueOf(number);
for(int i = 0; i < testCase.length(); i++) {
int digit = Integer.parseInt(String.valueOf(testCase.charAt(i)))*2;
str.append(digit);
}
return Integer.parseInt(str.toString());
}
}
So what's happening?
First, we convert the number to a String, so we can get each single character (as a number). The for loop will loop through every single character, and we can use a StringBuilder to append the character after it has been parsed to an int and multiplied by two.
In the above example, the program produces:
2468
When the test case is:
1234
And when the test case is:
9999
The result is:
18181818
This question already has answers here:
Converting Decimal to Binary Java
(26 answers)
Closed 6 years ago.
How can we convert int number, a decimal, to Binary? I'm learning Java & have the code below. Any advice? Thanks!
public static int decimalToBinary(int number) {
int result = 0;
while(number > 0){
int mod = number % 2;
result = result * 1 + mod;
number /= 2;
}
return result;
}
You can use the Integer.toBinaryString() method as follows,
int n = 100;
System.out.println(Integer.toBinaryString(n));
The Integer.toBinaryString() takes an int as a parameter and returns a String, so you can also do the following:
int n=100;
String s = Integer.toBinaryString(n);
System.out.println(s);
This will print it out to the screen, but you can just as easily assign it to a variable.
import java.util.Scanner;
public class ReversedBinary {
public static void main(String[] args) {
int number;
Scanner in = new Scanner(System.in);
System.out.println("Enter a positive integer");
number = in.nextInt();
if (number < 0) {
System.out.println("Error: Not a positive integer");
} else {
System.out.print("Convert to binary is:");
//System.out.print(binaryform(number));
printBinaryform(number);
}
}
private static void printBinaryform(int number) {
int remainder;
if (number <= 1) {
System.out.print(number);
return; // KICK OUT OF THE RECURSION
}
remainder = number %2;
printBinaryform(number >> 1);
System.out.print(remainder);
}
}
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! :)
I have to create a java program that converts binary to decimal using the following steps. Being new at this I did something, but I don't know what I did wrong or how to continue.
public class BinaryToDecimal {
public static void main(String args[]){
long sum = 0;
int result;
String s = "1001010101011010111001011101010101010101";
for(int i = s.length()-1; i <= 0; i--){
result = (int)Math.pow(2, i);
if(s.charAt(i) == '1')
sum=sum + result;
}
System.out.println(sum);
}
}
Use a loop to read (charAt()) each digit (0/1 char) in the input string, scanning from right to left;
Use the loop to build the required powers of 2;
Use a conditional statement to deal with 0 and 1 separately;
Debug using simple input, e.g. 1, 10, 101, and print intermediate values in the loop.
Use your program to find the decimal value of the following binary number:
1001010101011010111001011101010101010101
Do this only if your decimal value is at most 2147483647 or the maximum value an int can be in Java. If you don't know, just check the length of your string. If it's less than or equal to 32 i.e. 4 bytes, then you can use parseInt.:
int decimalValue = Integer.parseInt(s, 2);
Refer HERE for more info on the Integer.parseInt();
But if it's more, you can use your code. I modified your loop which is where your problem was:
String s = "1001010101011010111001011101010101010101";
long result = 0;
for(int i = 0; i < s.length(); i++){
result = (long) (result + (s.charAt(i)-'0' )* Math.pow(2, s.length()-i-1));
}
System.out.println(result);
The first thing I notice is that your binary number has more than 32 bits. This cannot be represented in the space of an int, and will result in overflow.
As a simpler answer, I ran the following and got the correct value at the end, it just uses simple bit shifts.
For each index in the string, if the character is 1, it sets the corresponding bit in the result.
public class BinaryToDecimal {
public static void main(String[] args) {
long sum;
String bin = "1001010101011010111001011101010101010101";
sum = 0;
for (int i = 0; i < bin.length(); i++) {
char a = bin.charAt(i);
if (a == '1') {
sum |= 0x01;
}
sum <<= 1;
}
sum >>= 1;
System.out.println(sum);
}
}
The loop runs from i = s.length()-1 until i <= 0. This should be i>=0.
The next problem is "int result". It works fine with result as a long ;) (Reason: You calculate a 40-bit value at the MostSignificantBit, but Integers only use 32-bit)
Also: You start at the rightmost Bit with i=s.length()-1. But the power that you calculate for it is 2^(s.length()-1) though it should be 2^0=1.
The solution is: result = (long)Math.pow(2, s.length()-1-i)
Edit:
I really like the solution of user2316981 because of its clear structure (without Math.pow, should be faster by using shift instead). And loops from 0 to MSB as I do with Double&Add algorithm. Can't comment on it yet, but thanks for the reminder ;)
import java.util.*;
import java.lang.Math;
class deci {
int convert(int n) {
int tem=1,power=0;
int decimal=0;
for (int j=0;j<n;j++) {
if(n==0) {
break;
} else {
while(n>0) {
tem=n%10;
decimal+=(tem*(Math.pow(2,power)));
n=n/10;
power++;
}
}
}
return decimal;
}
public static void main(String args[]) {
System.out.print("enter the binary no");
Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
deci dc=new deci();
int i=dc.convert(n);
System.out.print(i);
}
}
This problem has me puzzled. I tried using a loop like this: Basically I tried to get the first digit from the input and do the formula but it doesn't seem to work. It looks so simple but I can't figure it out. Could you help me? Thanks.
public static int ISBN(String ninedigitNum) {
number = 9;
while (number > 0) {
int nextDigit = ninedigitNum.substring(0,1);
...
}
Checksums (Source: Princeton University). The International Standard
Book Number (ISBN) is a 10 digit code that uniquely specifies a book.
The rightmost digit is a checksum digit which can be uniquely
determined from the other 9 digits from the condition that d1 + 2d2 +
3d3 + ... + 10d10 must be a multiple of 11 (here di denotes the ith
digit from the right). The checksum digit d1 can be any value from 0
to 10: the ISBN convention is to use the value X to denote 10.
Example: the checksum digit corresponding to 020131452 is 5 since is
the only value of d1 between 0 and and 10 for which d1 + 2*2 + 3*5 +
4*4 + 5*1 + 6*3 + 7*1 + 8*0 + 9*2 + 10*0 is a multiple of 11. Create a
Java method ISBN() that takes a 9-digit integer as input, computes the
checksum, and returns the 10-digit ISBN number. Create 3 JUnit test
cases to test your method.
I got it, thanks a lot everyone!
What about it isn't working? Either way, I believe what you're missing is that you're continually getting the same substring, which will be the first number of the string: int nextDigit = ninedigitNum.substring(0,1);. In addition, you're going to want to use an int, not a String; you can technically convert from String to int if desired, but the problem itself calls for an int.
There are two ways to do this that jump to mind. I would do this by realizing that mod in powers of 10 will give you the respective digit of an integer, but the easier way is to convert to a char array and then access directly. Note that there's no error checking here; you'll have to add that yourself. In addition, there are a LOT of 'magic numbers' here: good code typically has very, very few. I would recommend learning more data structures before attempting problems like these; to be honest there's very few things you can do without at least arrays and linked lists.
char[] ISBN = ninedigitNum.toCharArray();
//Process each number
int total = 0;
for(int i=0; i<9; i++){
int current_int = Integer.parseInt(ISBN[i]);
total += current_int * (10 - i)
}
//Find value of d1
for(int i=0; i<9; i++){
if(((total + i) % 11) == 0){
total += i*100000000;
break;
}
}
return total;
In general: Use print outs with System.out.println(x); or use your compiler's debugger to see what's going on during processing.
So,
This is the piece of code that I wrote. I still think it could be made more efficient.
public class Problem3 {
public static String ISBN(String x)
{
char[]temp = x.toCharArray();
int counter = 2;
int sum = 0;
int j=0;
for(int i=8;i>=0;i--)
{
sum+= counter*Integer.parseInt(""+temp[i]);
counter+=1;
}
for(j=0;j<10;j++)
{
if((sum+j)%11==0)
{
break;
}
}
return x+""+j;
}
public static void main(String args[])
{
String a = "020131452";
System.out.println(ISBN(a));
}
}
Hope this helps.
This works:
public static int ISBN(String nineDigitNum){
int sum = 0;
for(int i = 0; i<nineDigitNum.length(); i++){
sum += Integer.parseInt(""+nineDigitNum.charAt(i))*(10-i);
}
return (sum%11);
}
Also I believe if the checksum is == to 10, it should return an X, so you could either change the return type and add an if statement somewhere, or just put the if statement outside wherever you are using this method.
Here is a short one without loops that uses only substring(), charAt() and length():
public static String ISBN(String nineDigits) {
int chkD = 11 - checkDigit(nineDigits, 0);
return nineDigits + ((chkD == 10) ? "X" : chkD);
}
public static int checkDigit(String nDsub, int chkD) {
if (nDsub.length() == 0)
return 0;
chkD = ((nDsub.charAt(0) - '0') * (nDsub.length() + 1));
return (chkD + checkDigit(nDsub.substring(1), chkD)) % 11;
}
Output:
> ISBN("123456789")
"123456789X"
> ISBN("123456780")
"1234567806"