converting an array of integers into one long integer - java

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! :)

Related

Why Does my Palindrome Code not work? My reverse variable does what it is supposed to but I dont get true even when it is printing out a palindrome

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

How to convert integer into place values?

I have a problem here. I want to try to figure out how to take an integer, let's use 1234, and split into it's "place values." This means changing
1234
into
1000, 200, 30, 4
I am thinking about putting these into arrays, but im not sure what to do from there. My entire code will take any user input and turn it into roman numerals, and this is what i am thinking.
Try the below code
import java.util.*;
public class First
{
public static void main(String args[])
{
Scanner scan = new Scanner(System.in);
int num = scan.nextInt();
int i=1,mod;
while(num>0)
{
mod = num % 10;
System.out.println(mod*i);
i=i*10;
num = num/10;
}
}
}
This code will print the position value. You could store it in array other purpose.
this gives you the expected output, you could add the number to an arry using variable rem, the integer div is number of digits * 10
int num = 1234;
int div = (int) Math.pow(10, (int)(Math.log10(num)));
while(num > 0) {
int rem = num / div;
num = num % div;
div /= 10;
System.out.println("num : -> "+ rem);
}

Reverse integers in Java [duplicate]

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

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

Is there a function in java that works like SUBSTRING function but for integers?

is there a function in java that works like SUBSTRING function but for integers. Like for example the user's input is 456789, I want to break it into two part and put them into different variable. and divide them. for example,
user's input : 456789
the first 3 numbers will be in variable A.
the last 3 numbers will be in variable B.
pass = A/B;
can someone help me how can I do this,
thanks.
Use integer division and the modulus operator:
int input = 456789;
int a = input / 1000;
int b = input % 1000;
Here is a mathematical based implementation for positive and negative integers (probably can be optimized):
public static void main(String[] args) {
System.out.println(substring(2, 0, 1)); // prints "2"
System.out.println(substring(2523, 2, 2)); // prints "23"
System.out.println(substring(-1000, 0, 2)); // prints "-1"
System.out.println(substring(-1234, 0, 4)); // prints "-123"
System.out.println(substring(-1010, 2, 1)); // prints "0"
System.out.println(substring(-10034, 3, 2)); // prints "3"
System.out.println(substring(-10034, 2, 4)); // prints "34"
}
public static int substring(int input, int startingPoint, int length) {
if (startingPoint < 0 || length < 1 || startingPoint + length > size(input)) {
throw new IndexOutOfBoundsException();
}
if (input < 0 && startingPoint == 0 && length < 2) {
throw new IndexOutOfBoundsException("'-' can not be returned without a digit");
}
input /= (int) Math.pow(10, size(input) - length - startingPoint); // shift from end by division
input = input % (int) Math.pow(10, length); // shift from start by division remainder
if (input < 0 && startingPoint > 0) {
input = Math.abs(input); // update sign for negative input
}
return input;
}
private static int size(int input) {
int size = 1;
while (input / 10 != 0) {
size++;
input /= 10;
}
return input < 0 ? ++size : size; // '-'sign is a part of size
}
Splitting a "number" is not what you want to do. You want to split the NUMERAL, which is the string representing a quantity (number). You can split the numeral just like any other literal (string): don't parse the user's input and use substring. If you want to make sure the literal is an actual numeral, parse it to see if an exception is thrown. If not, you have a numeral. But don't hold on to the integers, keep the strings instead.
Here you go:
You give the method a number, start, and end indexes.
public static void main(String[] args) {
System.out.println(getPartOfInt(93934934, 3, 7));`
}
public static int getPartOfInt(int number, int start, int end){
Integer i = new Integer(number);
char[] chars = i.toString().toCharArray();
String str = "";
for(int j = start; j < end && j < chars.length; j++){
str += chars[j];
}
return Integer.parseInt(str);
}
OR:
public static int getPartOfInt(int number, int start, int end){
String str = new Integer(number).toString();
return Integer.parseInt(str.substring(start, Math.min(end, str.length())));
}
You could also first convert the number to String, like so:
int num = 456789;
String strNum = String.valueOf(num);
String part1 = strNum.substring(0, strNum.length() / 2 - 1);
String part2 = strNum.substring(strNum.length() / 2);
Then, you could convert it back to int, like so:
int part1Num = Integer.parseInt(part1);
int part2Num = Integer.parseInt(part2);
Now you can do all the arithmetic you want with those two int's.
#DeanLeitersdorf Here's the function ( #clcto s solution)
int subinteger(int input, int from, int size)
{
while (input > pow(10, size + from) - 1)
input /= 10;
return input % (int)pow(10, size);
}
This is a c++ solution but i hope that you can convert it to Java easily

Categories

Resources