This is a homework problem
How would I reverse an integer in Java with a for loop? The user will input the integer (I don't know how long it will be) and I need to reverse it. ie: If they enter 12345, my program returns 54321.
Here's the catch, you can't use String, StringBuffer, arrays, or other advanced structures in this problem.
I have a basic idea of what I need to do. My problem is...in the for loop, wouldn't the condition need to be x < the length of the integer (number of digits)? How would I do that without String?
Thanks for any input, and I'll add more information if requested.
EDIT:
Of course, after introspection, I realized I should use another for loop to do this. What I did was create a for loop that will count the digits by dividing by 10:
int input = scan.nextInt();
int n = input;
int a = 0;
for (int x = 0; n > 0; x++){
n = n/10;
a = a + 1;
}
EDIT 2:
This is what I have
int input = scan.nextInt();
int n = input;
int a = 0;
int r = 0;
for (int x = 0; n > 0; x++){
n = n/10;
a = a + 1;
}
for (int y = 0; y < n; y++) {
r = r + input%10;
input = input/10;
}
System.out.println(input);
When I run it, it isn't reversing it, it's only giving me back the numbers. ie: if I put in 1234, it returns 1234. This doesn't make any sense to me, because I'm adding the last digit to of the input to r, so why wouldn't it be 4321?
While your original number is nonzero, take your result, multiply it by 10, and add the remainder from dividing the original by 10.
For example, say your original number is 12345. Start with a result of 0.
Multiply result by 10 and add 5, giving you 5. (original is now 1234.)
Multiply result by 10 and add 4, giving you 54. (original is now 123.)
Multiply result by 10 and add 3, giving you 543. (original = 12.)
Multiply result blah blah 5432. (original = 1.)
Multiply, add, bam. 54321. And 1 / 10, in int math, is zero. We're done.
Your mission, should you choose to accept it, is to implement this in Java. :) (Hint: division and remainder are separate operations in Java. % is the remainder operator, and / is the division operator. Take the remainder separately, then divide the original by 10.)
You will need to use math to access each of the digits. Here's a few hints to get your started:
Use the % mod operator to extract the last digit of the number.
Use the / division operator to remove the last digit of the number.
Stop your loop when you have no more digits in the number.
This might not be the proper way but
public static int reverseMe(int i){
int output;
String ri = i + "";
char[] inputArray = ri.toCharArray();
char[] outputArray = new char[inputArray.length];
for(int m=0;m<inputArray.length;m++){
outputArray[inputArray.length-m-1]=inputArray[m];
}
String result = new String(outputArray);
output = Integer.parseInt(result);
return output;
}
public static void reverse2(int n){
int a;
for(int i = 0; i < n ; i ++){
a = n % 10;
System.out.print(a);
n = n / 10;
if( n < 10){
System.out.print(n);
n = 0;
}
}
}
here is the Answer With Correction of Your Code.
import static java.lang.Math.pow;
import java.util.*;
public class MyClass {
public static void main(String args[]) {
Scanner scan=new Scanner(System.in);
int input = scan.nextInt();
int n = input;
int a = 0;
int r = 0;
for (; n > 0;){
n = n/10;
a = a + 1;
}
for (int y = 0; y < input;a--) {
r =(int)( r + input%10*pow(10,a-1));
input = input/10;
}
System.out.println(r);
}
}
Related
The output is not showing the HCF but showing the initialized value that is 1.
package questionsOnLoops;
import java.util.Scanner;
public class hg {
public static void main(String[] args) {
Scanner srv = new Scanner(System.in);
System.out.print("Enter the first number: ");
int n1 = srv.nextInt(); //first number
System.out.println("Enter the second number: ");
int n2 = srv.nextInt(); //second number
int HCF=1; // Highest Common factor
int s; //smaller of two number
s = Math.min(n1, n2);
for(int i = s; i <= 1 ; i--) {
if(n1%i==0&&n2%i==0) {
HCF=i;
break;
}
}
System.out.println(HCF);
}
}
for(i = 1; i <= a || i <= b; i++) {
if( a%i == 0 && b%i == 0 )
hcf = i;
}
Use this logic. here a is the first number and b is the second.
Your code is never executing the "for" loop because you set i=s and i will never be i<=1...
Change to i>=1 and you're good to go
You have just to change your operator in your 'for' loop.
for(int i = s; i >= 1 ; i--) {
Because in your code you loop while i is less than 1. But in your inizialization i is equal to s. So you never enter in the 'for' loop and your HCF is the default value of your HCF variable which is 1.
For your culture if you want an optimized way to calculate the HCF, you can use the Euclidean algorithm which reduce drastically the number of operation. Because you transform several division and condition into a few Euclidean division.
Here an exemple
public int hcf(int m, int n) {
// the remainder of the Euclidean division
int r = 0;
// The algorithm says "the HCF of m and n is the last non-zero remainder"
while(n != 0) {
r = m % n;
m = n;
n = r;
}
return m;
}
I am trying to figure out how to write my code that it reads from the right to left, not left to right
public static int sumofEvenSpot(long number)
{
int sumEvenSpot = 0;
String stringLength = Long.toString(number);
for (int i = 0; i< stringLength.length(); i += 2)
sumEvenSpot += (getDigit(Character.getNumericValue(stringLength.charAt(i)) * 2));
return sumEvenSpot;
}
Just do for(int i = stringLength.length() - 1; i = 0; i = i - 2)
( for(start, end, increment) )
OR
You can reverse your string and do a normal for but it takes more code
You can start summing from the rightmost digit, and every iteration divide the number by 100 in order to remove the current digit and the next one (in the odd place) in order to keep summing the following even digit:
int sum = 0;
while(number > 0) {
sum += number % 10;
number /= 100;
}
One advantage of doing it this way is that you don't have to convert the long to string and then back to int.
I have a serious problem. I need to get a number say
123454466666666666666665454545454454544598989899545455454222222222222222
and give the total of that number. I was trying for a long time. I couldn't get the answer. The problem is I didn't know which data type to use. I have tried it long. It accepts only 18 digits. I have gone through BigInteger. But I couldn't make arithmetic operations with it. so help me out with this problem..
1.Get it as a string
2.get length of it.
3.Loop through each character of it.
4.check if the character is a number.
5.If yes parse it to int.
6.Add all numbers together in the loop
OR
Use BigDecimal
You can get the result from the below code.
String string = "123454466666666666666665454545454454544598989899545455454222222222222222";
int count = 0;
for (int i = 0; i < string.length(); i++) {
count += Integer.parseInt(String.valueOf(string.charAt(i)));
}
System.out.println(count);
Just use it as a String. That's the easiest way to go for the task at hand.
public class Test022 {
public static void main(String[] args) {
String s = "123454466666666666666665454545454454544598989899545455454222222222222222";
int sum = 0;
for (int i=0; i<s.length(); i++){
sum += s.charAt(i) - '0';
}
System.out.println(sum);
}
}
i can suggest using this code and the numbers as String
/**
* Adds two non-negative integers represented as string of digits.
*
* #exception NumberFormatException if either argument contains anything other
* than base-10 digits.
*/
public static String add(String addend1, String addend2) {
StringBuilder buf = new StringBuilder();
for ( int i1 = addend1.length() - 1, i2 = addend2.length() - 1, carry = 0;
(i1 >= 0 && i2 >= 0) || carry != 0;
i1--, i2-- ) {
int digit1 = i1 < 0 ? 0 :
Integer.parseInt(Character.toString(addend1.charAt(i1)));
int digit2 = i2 < 0 ? 0 :
Integer.parseInt(Character.toString(addend2.charAt(i2)));
int digit = digit1 + digit2 + carry;
if (digit > 9) {
carry = 1;
digit -= 10;
} else {
carry = 0;
}
buf.append(digit);
}
return buf.reverse().toString();
}
BigInteger does support methods like add/multiply etc. See this for details.
BigInteger operand1 = new BigInteger("123454466666666666666665454545454454544598989899545455454222222222222222");
BigInteger operand2 = new BigInteger("123454466666666666666665454545454454544598989899545455454222222222222222");
System.out.println(operand1.add(operand2));
System.out.println(operand1.subtract(operand2));
System.out.println(operand1.multiply(operand2));
System.out.println(operand1.divide(operand2));
How would I add together two integers with different number of digits, using an array, without causing an out of bounds exception?
For example: 500 + 99
each digit is an element of the array
This is how I'm doing it right now:
int aIILength = infiniteInteger.length-1;
int bIILength = anInfiniteInteger.infiniteInteger.length-1;
for(int f = aIILength; f >0; f--){
int aTempNum = infiniteInteger[f];
int bTempNum = anInfiniteInteger.infiniteInteger[f];
result = aTempNum + bTempNum;
//array representation of sum
tempArray[f] = result;
}
Let the counter in the loop go from 1 and up, and use it to access the digits from the end of each array.
You need a carry to hold the overflow of adding each set of digits.
Loop until you run out of digits in both arrays, and carry is zero.
Check the range when you access the digits from the arrays, and use zero when you run out of digits.
int aIILength = infiniteInteger.length;
int bIILength = anInfiniteInteger.infiniteInteger.length;
int carry = 0;
for(int f = 1; f <= aIILength || f <= bIILength || carry > 0; f++){
int aTempNum;
if (f <= aIILength) {
aTempNum = infiniteInteger[aIILength - f];
} else {
aTempNum = 0;
}
int bTempNum;
if (f <= bIILength) {
bTempNum = anInfiniteInteger.infiniteInteger[bIILength - f];
} else {
bTempNum = 0;
}
result = aTempNum + bTempNum + carry;
tempArray[tempArray.length - f] = result % 10;
carry = result / 10;
}
Note: Make tempArray longer than both the operand arrays, so that it has place for a potential carry to the next digit.
I am trying to create a program that will tell if a number given to it is a "Happy Number" or not. Finding a happy number requires each digit in the number to be squared, and the result of each digit's square to be added together.
In Python, you could use something like this:
SQUARE[d] for d in str(n)
But I can't find how to iterate through each digit in a number in Java. As you can tell, I am new to it, and can't find an answer in the Java docs.
You can use a modulo 10 operation to get the rightmost number and then divide the number by 10 to get the next number.
long addSquaresOfDigits(int number) {
long result = 0;
int tmp = 0;
while(number > 0) {
tmp = number % 10;
result += tmp * tmp;
number /= 10;
}
return result;
}
You could also put it in a string and turn that into a char array and iterate through it doing something like Math.pow(charArray[i] - '0', 2.0);
Assuming the number is an integer to begin with:
int num = 56;
String strNum = "" + num;
int strLength = strNum.length();
int sum = 0;
for (int i = 0; i < strLength; ++i) {
int digit = Integer.parseInt(strNum.charAt(i));
sum += (digit * digit);
}
I wondered which method would be quickest to split up a positive number into its digits in Java, String vs modulo
public static ArrayList<Integer> splitViaString(long number) {
ArrayList<Integer> result = new ArrayList<>();
String s = Long.toString(number);
for (int i = 0; i < s.length(); i++) {
result.add(s.charAt(i) - '0');
}
return result; // MSD at start of list
}
vs
public static ArrayList<Integer> splitViaModulo(long number) {
ArrayList<Integer> result = new ArrayList<>();
while (number > 0) {
int digit = (int) (number % 10);
result.add(digit);
number /= 10;
}
return result; // LSD at start of list
}
Testing each method by passing Long.MAX_VALUE 10,000,000 times, the string version took 2.090 seconds and the modulo version 2.334 seconds. (Oracle Java 8 on 64bit Ubuntu running in Eclipse Neon)
So not a lot in it really, but I was a bit surprised that String was faster
In the above example we can use:
int digit = Character.getNumericValue(strNum.charAt(i));
instead of
int digit = Integer.parseInt(strNum.charAt(i));
You can turn the integer into a string and iterate through each char in the string. As you do that turn that char into an integer
This code returns the first number (after 1) that fits your description.
public static void main(String[] args) {
int i=2;
// starting the search at 2, since 1 is also a happy number
while(true) {
int sum=0;
for(char ch:(i+"").toCharArray()) { // casting to string and looping through the characters.
int j=Character.getNumericValue(ch);
// getting the numeric value of the current char.
sum+=Math.pow(j, j);
// adding the current digit raised to the power of itself to the sum.
}
if(sum==i) {
// if the sum is equal to the initial number
// we have found a number that fits and exit.
System.out.println("found: "+i);
break;
}
// otherwise we keep on searching
i++;
}
}