reversing digits numbers in java [duplicate] - java

This question already has answers here:
Java reverse an int value without using array
(33 answers)
Closed 8 years ago.
I've looked around and came up with this solution, but it doesn't seem to be working. Does anyone have an idea? I need to get a number from the user that is only 3 digits and positive. after that, to reverse the 3 digits. what i wrote below only give me the last digit out of the three that I need.
int reversedNum=0;
Scanner scan = new Scanner (System.in);
System.out.println("Please enter a 3 digit positive number whose first and last digits are different: ");
int userNumber = scan.nextInt();
if (userNumber >= 100 && userNumber <= 999)
{
System.out.println("User number is: " + userNumber);
reversedNum = (reversedNum*10) + (userNumber%10);
userNumber = userNumber/10;
System.out.println("Difference "+reversedNum);
}
else
System.out.println("The number you entered is not a 3 digit positive number");

When you do
reversedNum = (reversedNum*10) + (userNumber%10);
userNumber = userNumber/10;
reversedNum is 0 so you end up with only userNumber%10.
You need something like this:
int hundreds = (int)(userNumber/100);
int remaining = userNumber-100*hundreds;
int dec = (int)(remaining /10);
remaining -= 10*dec;
int reversed = 100*remaining + 10*dec + hundreds
System.out.println("Reversed: " + reversed);
System.out.println("Difference " + (userNumber-reversed);

You can use % operator in order to print the last digit of input and then use / between int operand to get remaining digits
while(input%10 != input) {
int mod = input % 10;
System.out.print(mod);
input /= 10;
}

String result = "" + Integer.toString(userNumber).charAt(2) + Integer.toString(userNumber).charAt(1) + Integer.toString(userNumber).charAt(0);
int reversedNum = Integer.valueOf(result);
That will reverse your integer.

To reverse the number the logic should be as below. Use % and / operator to find the individual digit.
if (userNumber >= 100 && userNumber <= 999)
{
System.out.println("User number is: " + userNumber);
int unitdigit = userNumber%10;
userNumber = userNumber/10;
int tenthdigit = userNumber%10;
int lastdigit = userNumber/10;
reversedNum = (unitdigit*100) + (tenthdigit*10) + lastdigit;
System.out.println("reversed numnber "+reversedNum);
}

Related

Separating numbers using %

I am trying to get 3 numbers separated by a space after user's input. I can get the first number and the last one dividing by 10, but I really have no idea how to get the middle number
I tried to take the remainder of the first two numbers and then divide them by ten, but IDEA says that the answer is always zero
public static void main(String[] args) {
System.out.println("Input the number");
int number = read.nextInt();
int a = number%10;
int b = (number%10)/10; // the answer is always 0
int c = number / 100;
System.out.println(c + " " + b + " " + a);
}
Anything modulo 10 will return a result in the range of 0 to 9, and (integer) dividing that by 10 will return 0. You need to reverse the order - first divide the 10 to remove the last digit, and then take the remainder from 10 to keep the middle digit:
int b = (number / 10) % 10;
I suggest using this instead of %. Because you can split and get any digit of number using this code:
int x=158;
char[] xValueInString = Integer.toString(x).toCharArray();
for(int i=0; i<xValueInString.length; i++){
System.out.println(xValueInString[i]);
}
You missed scanner in your code, add Scanner before reading number, try this with little change
public static void main(String[] args) {
System.out.println("Input the number");
Scanner read = new Scanner(System.in);
int number = read.nextInt();
int a = number%10;
int b = (number/10)%10; // the answer is always 0
int c = number/100;
System.out.println(c + " " + b + " " + a);
}

Trying to make a program that can pick out the top two numbers [duplicate]

This question already has answers here:
Printing the two highest values from user input
(4 answers)
Finding the two highest numbers based on input
(8 answers)
Closed 8 months ago.
import java.util.Scanner;
public class TopTwo {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter a sequence of numbers: ");
int max = Integer.MIN_VALUE;
int min = Integer.MAX_VALUE;
int first = Integer.MIN_VALUE;
int firstOccurences = 0;
int second = Integer.MAX_VALUE;
int secondOccurences = 0;
while(input.hasNextInt()){
int x = input.nextInt();
if(x > first){
first = x;
firstOccurences = 1;
}
else if (x == first){
firstOccurences += 1;
}
if(x>second){
second = x;
secondOccurences = 1;
}
else if(x<first){
secondOccurences += 1;
}
}
System.out.println("The highest is " + first + ". Its number of occurences is " + firstOccurences);
System.out.println("The second highest is " + second + ". Its number of occurrences is " + secondOccurences);
}
}
I'm trying to finish this code but I cannot figure out how to pick out the second highest number and could use some help, it can pick out the top value but not the second so far also it allows user input until anything besides a number is typed eg. fin .
Input: 24,56,62,12,79,-19,-12,-5,5,fin;
Output:The highest is 79. Its number of occurences is 1
The second highest is 2147483647. Its number of occurrences is 5.

The sum of all odd digits of an input [duplicate]

This question already has answers here:
How do I find the sum of all odd digits of user input numeric string?
(5 answers)
Closed 2 years ago.
How to compute the sum of all 'odd digits of an input' using 'loop'. (For example, if the input is 32677, the sum would be 3 + 7 + 7 = 17.)
I can't quite figure out how to do that, can someone please help me out. This is what I have done so far, I don't know how to complete it or whether I have its right or wrong.
Any help would be appreciated!
System.out.println("Enter a number: ");
String input = in.nextLine();
int length = input.length();
int sum = 0;
int digits = 0;
for (int i = 0; i < length; i++) {
if (length % 2 == 1) {
digits += i;
sum = digits++;
}
}
System.out.println(sum);
Here comes a Java8-based solution:
final int result = input.chars()//make a stream of chars from string
.mapToObj(String::valueOf) // make every character a String to be able to use parseInt later
.mapToInt(Integer::parseInt) // transform character in int
.filter(i -> i % 2 == 1) // filter out even numbers
.sum();
You don't need to use String if your input is not so long.
also for safe side use long datatype.
Here is the working code with comments (explain each step).
long sumOddDigits(long value){
long temp = value; // copy in temp variable
long sum = 0;
while(temp > 0){
int digit = temp%10; // get last digit of number. example: 227 gives 7.
temp = temp / 10; // remove that last digit from number.227 will be 22.
if(digit % 2 == 1){
sum += digit;
}
}
return sum;
}
Your interpretation of the digits inside of input is not working this way.
System.out.println("Enter a number: ");
String input = in.nextLine();
int length = input.length();
int sum = 0;
for (int i = 0; i < length; i++) {
int digit = input.charAt(i) - '0';
if (digit % 2 == 1) {
System.out.println("Add digit: " + digit);
sum += digit;
}
}
System.out.println(sum);
In your loop, use Integer.parseInt(input.charAt(i)) to get the number at position i.
if(length%2==1){ that doesn't make sense here. You want to check if your number is odd, not the length of your string.

Java - Write a program that prompts the user to input an integer and then outputs both the individual digits of the number and the sum of the digits

I have seen this question asked a few times, but all of the responses have included functionality that I haven't learned yet in this class and am I sure there must be a way to do it with only what I have learned. No arrays, etc... just loops and prior. I am not really looking for the answer, but just some direction. I have included the code I have already done. The program needs to be able to hand negative numbers, the sum and then print in the proper order. Right now my code does everything except print in the proper order. I understand why it is printing in reverse order (because the loop gets rid of and then prints the last number in the int), but I can't seem to figure out a way to change it. I have tried converting it to a string, char and just can't get it. Please take a look, and provide some guidance if you don't mind. thank you in advance.
public static void main(String[] args) {
int num;
int sum;
int temp;
System.out.print("Enter an integer, positive or negative: ");
num = keyboard.nextInt();
System.out.println();
if (num < 0)
num = -num;
sum = 0;
while (num > 0) {
temp = num;
sum = sum + num % 10; //Extracts the last digit and adds it to the sum
num = num / 10; //removes the last digit
System.out.print(temp % 10 + " ");
}
System.out.println(" and the sum is " + sum);
}
}
Not knowing what they've taught you in class so far, an easy albeit inefficient thing to do is to recreate the number as string.
String numbers = "";
while (num > 0) {
temp = num;
sum = sum + num % 10; //Extracts the last digit and adds it to the sum
num = num / 10; //removes the last digit
// System.out.print(temp % 10 + " ");
numbers = (temp % 10) + " " + numbers;
}
System.out.println(numbers + "and the sum is " + sum);
You were already grabbing the ones digit with (temp % 10) and then right shifting the original number with num = num / 10. There are other data structures you could use like a Stack or a LinkedList that are more natural to use in a situation like yours, or you could use a StringBuilder to append the digits to the end and then use the reverse() method to get them back in the correct order, but those data structures probably come after Arrays which you mentioned you didn't know.
Given those constraints, I used String concatenation. In general here is what happens:
String numbers = "";
num = 123;
digit = num % 10; // digit=3
num /= 10; // num=12
numbers = digit + " " + numbers; // numbers="3 " uses old value on right side of the equals
// next iteration
digit = num % 10; // digit=2
num /= 10; // num=1
numbers = digit + " " + numbers; // numbers="2 3 " see how the digit is put to the left of the old value
// last iteration
digit = num % 10; // digit=1
num /= 10; // num=0
numbers = digit + " " +numbers; // numbers="1 2 3 " notice there is an extra space at the end which is ok for your example
Set a counter, loop num/10, if result>0 counter++. In the end, counter+1 will be the number of digits
System.out.println("Please enter numbers: ");
int number_entered = input.nextInt();
int sum = 0;
String reserve = "";
if (number_entered < 0 ) {
number_entered = number_entered * -1;
}
for (number_entered = number_entered; number_entered > 0; number_entered/=10){
int lastdgt = number_entered%10;
sum += lastdgt;
reserve = lastdgt + " " + reserve + " ";
}
System.out.println(reserve);
System.out.println("The sum is = " + sum );
}
}

Luhn's algorithm [duplicate]

This question already has answers here:
Check Credit Card Validity using Luhn Algorithm
(13 answers)
Closed 8 years ago.
a) Starting with the check digit and moving left, compute the sum of all the decoded digits.
b) Compute the remainder of the sum using integer division by 10. If the result is not zero, the credit card number is invalid. Otherwise, the card number is likely to be valid.
Here are two examples:
Card number: 2315778 Card number 1234567
decode(8, false) = 8 decode(7, false) = 7
decode(7, true) = 5 decode(6, true) = 3
decode(7, false) = 7 decode(5, false) = 5
decode(5, true) = 1 decode(4, true) = 8
decode(1, false) = 1 decode(3, false) = 3
decode(3, true) = 6 decode(2, true) = 4
decode(2, false) = 2 decode(1, false) = 1
Sum = 30 Sum = 31
30 mod 10 = 0 31 mod 10 = 1
This number may be valid This number is invalid
Write a static method called checkDigits that is passed a seven-digit credit card number and that performs the steps described above. Reuse the decode method that you wrote in Lab 5.5.1. The method should return the word “valid” if the number passes the test and “invalid” otherwise.
import java.util.Scanner;
public class JavaApplication90
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
int num = 2315778;
System.out.println("Credit card number: " + num + " is " + checkDigits(num));
num = 1234567;
System.out.println("Credit card number: " + num + " is " + checkDigits(num));
num = 7654321;
System.out.println("Credit card number: " + num + " is " + checkDigits(num));
num = 1111111;
System.out.println("Credit card number: " + num + " is " + checkDigits(num));
}
public static boolean checkDigits(int num)
{
int sum = 0;
String reverse = new StringBuffer(num).reverse().toString();
for (int i = 0; i < reverse.length(); i++){
int product = 0;
if (i % 2 == 0)
{
product = num * 2;
}
if (product < 9)
product = (product%10)-1;
sum = sum+ product ;
}
return (sum % 10 == 0);
}
}
Output:
I am getting true/valid answer for all numbers. I am not able to find my error. Help!
There are at least three issues.
You don't set product in the case where i is odd; so in that case, product will be 0 and the sum will be wrong.
You don't actually look for the ith digit of num. You're just using num wholesale each time you refer to it, whereas you should be using something like reverse.charAt(i) instead.
The StringBuffer that you're creating is actually empty - the constructor that you've used doesn't do what you think it does. This means that you're not iterating the for loop at all. You should probably check the Javadocs for a more suitable StringBuffer constructor to use.

Categories

Resources