How to calculate the double of digits from an integer in Java? - java

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

Related

output is not correct(Swapping the first and last digit of a number)

the output is almost correct except the first digit is not being removed.
the code should swap the first and last digit of the number for example - if the input is 756 it should give 657 as output right now the code is showing 7657 the first digit is not being removed. –
package questionsOnLoops;
import java.lang.Math;
import java.util.Scanner;
public class OSJIDS {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner srv = new Scanner(System.in);
System.out.println("Enter any number: ");
int n = srv.nextInt();
int temp = n; //input number
int c = 0;
int f =n; //first digit
int l; //last digit
int result;
while(temp>0) {
temp = temp/10;
c = c+1;
}
while(f>=10) {
f = f/10;
}
g = n%10;
result = (n/10)*10+f;
result = (int) ((result%Math.pow(10,c))+(g*Math.pow(10,c)));
System.out.println(result);
}
}
I do recommend making your variables a bit more descriptive, but that is an easy fix. I am guessing from your title that you want to swap the first and last digits? This method converts the numbers to strings, making appends and insertions relatively easier in this case.
import java.util.*;
import java.io.*;
class Main {
public static void main(String[] args) {
Scanner srv = new Scanner(System.in);
System.out.println("Enter any number: ");
int num = srv.nextInt();
int lastDig = num;
int firstDig = num%10;
int len = 0;
while(lastDig>9) {
lastDig/=10;
len++;
}
String ans = Integer.toString(num).substring(1, len);
ans = firstDig+ans+lastDig;
System.out.println(ans);
}
}
Let’s use your example input, 756.
This gets rid of the last digit, 6, and instead puts the first digit there:
result = (n/10)*10+f;
So now result is 757. Next you try to put the 6 where the first 7 is:
k = (int) ((result%Math.pow(10,c))+(g*Math.pow(10,c)));
This isn’t quite correct. c is 3, the number of digits. So Math.pow(10,c) equals 1000.0. But you needed to use 100 in those two places, first to get rid of the 7 and then to add the 6 there. Try subtracting 1 from c in the expression.
My suggestions for more readable code
Don’t declare a variable until you use it; inirialize each in the declaration.
Use better variable names. For example:
input rather than n
length or numberOfDigits instead of c
firstDigit instead of f
lastDigit instead of g
lastDigitReplaced instead of result
finalResult instead of k
Your code makes it quite hard to see what is exectly happening.
There are a few problems I see in your code (next to readability).
You were able to detect the first and the last number, but getting to the result seems to contain some mistakes
result = (input/10)*10+f; here you take the input (506), you divide it by 10, multiply it by 10 to abuse the the int so that your fractions are removed and restored to the original number. Then you append the first number again.
With the calculation you did above, you removed the last number, and added the first number as the last number. You are still missing the step to add the first number. It would be easier and better to just create a new number based on your calculations
Calculating the new number
You already have most of the ingredients to calculate the new number.
You already have the firstDigit and the last digit calculated. To get to the result we take the last number, and multiply it with 10 until it's in the correct position to be first.
Next we append the first number, so that it's last in our new number
finally, we add the inbetween numbers again. (you can calculate the inbetween numbers by removing the first and last number from the original input)
I've updated your code example with the above mentioned changes. I've also gave the variables a bit more clear names to indicate what they contain
public static void main(String[] args) {
Scanner srv = new Scanner(System.in);
System.out.println("Enter any number: ");
int input = srv.nextInt();
int temp = input;
int length = 0;
int firstDigit =input;
int lastDigit;
int inbetweenNumbers;
while(temp>0) {
temp = temp/10;
length = length+1;
}
while(firstDigit>=10) {
firstDigit = firstDigit/10;
}
lastDigit = input%10;
inbetweenNumbers = input - lastDigit;
inbetweenNumbers -= firstDigit * (int)Math.pow(10,length-1);
//calculating the result
int result = 0;
result += lastDigit * (int)Math.pow(10,length-1);
//Add last number (first digit of the input)
result += firstDigit;
//add the other numbers back
result+= inbetweenNumbers;
System.out.println(result+" "+length);
}

How to swap digits in java

I am trying to practice java over the summer and i'm stuck on this problem. I need to swap the 2 letters in a integer in java. For example in my main method I make a method called swapdigits and have my parameters as 1432. The program should swap the 4 and 1 and 3 and 2. The output should be 4123 since it swapped the two letters in order. Lets say I do swapdigits(1341234) the output should be 3114324. I know I have to use while loops but i'm getting stuck on the swapping.
This is what I have so far:
public static void main(String[] args) {
Swapdigits(2413);
}
public static void Swapdigits(int number){
while(number>0){
int y=number/1000;
int x=number%10;
int original=number-y;
System.out.println(original);
}
System.out.println();
}
}
public static int swapDigitPairs(int number) {
int result = 0;
int place = 1;
while (number > 9) {
result += place * 10 * (number % 10);
number /= 10;
result += place * (number % 10);
number /= 10;
place *= 100;
}
return result + place * number;
}
You can also try
char[] a = String.valueOf(number).toCharArray();
for (int i = 0; i < a.length - 1; i += 2) {
char tmp = a[i];
a[i] = a[i + 1];
a[i + 1] = tmp;
}
int number = Integer.parseInt(new String(a));
Because you're just swapping the places of digits, it doesn't actually matter what the number is. So, it's probably easier (and makes more sense) to represent the argument as a string. That way you aren't dealing with weird modulo operators - If you were solving the problem by hand, would you actually do any math? You'd treat this problem the same whether it were numbers of a bunch of characters.
Take a look at the following question for information on swapping characters in a String:
How to swap String characters in Java?

Java program that converts binary numbers to decimal numbers. The input is a string of zeros and ones

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);
}
}

Checksums - ISBN program

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"

how to get an array of of the digits of an int in java

So this probably would be easy if done like this
public static [] nums(int j)
{
int num = 12345;
int[]thenums = [5];
for(int i=0; i<5; i++)
{
thenums[4-i] = num%10;
num = num/10;
}
return the nums
}
i get {1,2,3,4,5}
but for some reason if the number starts with a 0 then it does not work
how to make this work if the number were
int num = 02141;
thanks
EDIT: Doh... I'd completely forgotten about octal literals. That explains why the value is showing up differently. (02141 is treated as an octal literal; it's not the same value as 2141.)
However, it sounds like the OP wants to "remember" the number of leading zeroes in a number. There's no way of doing that as an integer, because it's just remembering a value. What's the difference between seeing "3" birds and seeing "0000003" birds?
If you have a number representation where the leading zeroes are important, you're not just talking about an integer quantity, which is all that an int represents.
Where are you getting your input from? It sounds like you should just be maintaining it as a string from the start.
If you always want 5 digits, that's easy to do - and your current code should do it (when amended to actually compile) - something like this:
public class Test
{
public static void main(String[] args)
{
int[] digits = getDigits(123);
for (int digit : digits)
{
System.out.print(digit); // Prints 00123
}
}
public static int[] getDigits(int value)
{
int[] ret = new int[5];
for (int i = 4; i >=0 ; i--)
{
ret[i] = value % 10;
value = value / 10;
}
return ret;
}
}
Now that's hard-coded to return 5 digits. If you don't know the number of digits at compile-time, but you will know it at execution time, you could pass it into the method:
public static int[] getDigits(int value, int size)
{
int[] ret = new int[size];
for (int i = size - 1; i >=0 ; i--)
{
ret[i] = value % 10;
value = value / 10;
}
// Perhaps throw an exception here if value is not 0? That would indicate
// we haven't captured the complete number
return ret;
}
What happens in your code is that 02141 is not the same as 2141; the first is octal (equivalent to 1121 decimal), while the second is 2141 decimal.
The relevant part of the Java Language Specification is JLS 3.10.1, specifically the grammar productions for DecimalNumeral and OctalNumeral.

Categories

Resources