How to properly align and format varying string lengths - java

How can I apply string.format and printf to my output so that I can align it as per my assignment requirement?
I have 3 inputs to my method, 2 of which are char arrays which hold the two numbers, and an int array which holds their sum.
I have formatted the numbers and sum so that it is a string with appropriate commas interspersed. My task is to now align these outputs so that they always align themselves properly. The problem is I can't just set the column width to a specific number seeing as the inputs vary due to user input.
Ex: User inputs number1 and number2 (up to a max value of 30 digits), the program sums up the numbers and returns the total.
This is my code and current output:
import java.util.Scanner;
import java.util.Arrays;
public class Lab8{
public static void main(String[] args){
char[] num1 = {'9','2','3','8','7','4','8','6','7','2','9'};
char[] num2 = {'3','9','9','8','3','9','2','8','3','4','9','4','5','8'};
//getNumber("First Number: ");
//getNumber("Second Number: ");
//printArray(num1);
//System.out.println();
//printArray(num2);
int[] finalTotal = sumArrays(num1,num2);
//sumArrays(num1, num2);
printOutput(num1, num2, finalTotal);
}
//--------
/** Read a line of message from keyboard and return it as an array of char
#return: Array of characters
*/
public static char[] getNumber(String msg){
String myMessage;
System.out.print(msg);
Scanner input = new Scanner(System.in);
myMessage = input.nextLine();// Read a line of message
return myMessage.toCharArray();
}
public static int[] sumArrays(char[] num1, char[] num2){
int sum= 0, carry = 0, size = 0, min = 0;
if(num1.length > num2.length){
size = num1.length + 1;
min = num2.length;
}else{
size = num2.length + 1;
min = num1.length;
}
int[] sumArray = new int[size];
int i = num1.length-1;
int j = num2.length-1;
int k = size-1;
while(i >= 0 && j >=0){
sum = Character.getNumericValue(num1[i]) + Character.getNumericValue(num2[j]) + carry;
i--;
j--;
sumArray[k] = sum % 10;
sum = sum / 10;
carry = sum % 10;
k--;
}
while(i >= 0){
sum = Character.getNumericValue(num1[i]) + carry;
sumArray[k] = sum % 10;
sum = sum / 10;
carry = sum % 10;
i--;
k--;
}
while( j >= 0){
sum = Character.getNumericValue(num2[j]) + carry;
sumArray[k] = sum % 10;
sum = sum / 10;
carry = sum % 10;
j--;
k--;
}
sumArray[k] = carry;
int[] finalSum = new int[sumArray.length-1];
finalSum = printArray(sumArray);
return finalSum;
}
public static void printOutput(char[] num1, char[] num2, int[] sum){
char[] largest = new char[1];
char[] smallest = new char[1];
char[] tmp = new char[1];
if(num2.length > num1.length){
largest = num2;
smallest = num1;
}else{
largest = num1;
smallest = num2;
}
String number1 = formatString(largest);
String number2 = formatString(smallest);
String total = formatString(sum);
System.out.printf("%s%n", number1 + " +");
for(int i = 0; i < (number1.length() - number2.length()); i++){
System.out.print(" ");
}
System.out.printf("%s%n%s%n%s", number2, totalLine(sum),total);
}
public static String formatString(char[] num){
String formattedString = "";
for(int i = 0; i < num.length; i++){
if(i == 0){
formattedString = num[num.length-1-i] + formattedString;
continue;
}
if(i % 3 == 0){
formattedString = "," + formattedString;
}
formattedString = num[num.length-1-i] + formattedString;
}
return formattedString;
}
public static String totalLine(int[] num){
String totalLine = "";
for(int i = 0; i < num.length; i++){
totalLine = "- " + totalLine;
}
return totalLine;
}
public static String formatString(int[] num){
String formattedString = "";
for(int i = 0; i < num.length; i++){
if(i == 0){
formattedString = num[num.length-1-i] + formattedString;
continue;
}
if(i % 3 == 0){
formattedString = "," + formattedString;
}
formattedString = num[num.length-1-i] + formattedString;
}
return formattedString;
}
public static int[] printArray(int[] arr){
int[] sum = new int[arr.length-1];
if(arr[0] == 0){
for(int i = 1; i < arr.length; i++){
sum[i-1] = arr[i];
}
}else{
for(int i = 0; i < arr.length; i++){
sum[i] = arr[i];
}
}
return sum;
}
}
OUTPUT(wrong)
39,983,928,349,458 +
92,387,486,729
- - - - - - - - - - - - - -
40,076,315,836,187
OUTPUT(correct way)
39,983,928,349,458 +
92,387,486,729
--------------------
40,076,315,836,187
As you can see, my formatting is flawed. I'm totally unsure how to properly format this output so that it displays correctly every time even with differing number values. It should be formatted with the larger number above the smaller number and then a total line followed by the sum.

So after reading some more I realized what I was trying to achieve didn't necessarily require string formatting or printf statements. I ended up, like the previous comments and answer above suggested, just formatting the output with multiple print statements. It's definitely not the most beautiful code to look at but it gives me the exact output I was after.
This was the code that did the trick:
System.out.println(" " + number1 + " +");
for(int i = 0; i < (number1.length() - number2.length()); i++){
System.out.print(" ");
}
System.out.println(" " + number2);
System.out.print(" ");
for(int j = 0; j < ((number1.length() - number2.length())+ number2.length()+1); j++){
System.out.print("-");
}
System.out.println();
System.out.print(" " + total);

Based on your comments, it seems like the math is tripping you up. Let me see if I can help.
(You implied this was homework, so I'm not going to literally give you the code, but this should set you on the right path. I'm sure you can implement it yourself.)
The number of digits in a number is:
Math.floor(Math.log10(x)) + 1
(See this conversation for a proof.)
Use that to find the length of the answer. (This is always going to be the longest number or tied for the longest, since you're adding numbers together.) Make your line of ---s this long.
Append to the front of each line length of that line - length of the answer number of spaces.
(If you want to have a certain number of spaces as an indent on the whole problem, as you have in your example, then append length of line - length of answer + indent number of spaces to the front of each line instead.)
Append + (space and a plus) to the end of the first line, and (two spaces) to the other lines.
That should work!

You can use ArrayLists instead of char arrays to simplify math. But you have to adjust the code a bit. Here is the procedure.
Get two lines of inputs in to two array lists using getNumber() method. (let's call the B and C)
Take the sum to a third array list using the sum method.(Let's call A)
Find the sizes of array lists using size() method in arraylist.
Compare the sizes and get the difference between biggest array list and other two array lists seperately.(Largest would be A so get A-B and A-C). And store sizes B and C sizes for future use in two variables.
Add (A-B) number of whitespaces(" ") into B arraylist staring from 0 index using add(index,object) method in array list.(in add(index,object) method shifts the element currently at that position (if any) and any subsequent elements to the right)
Do the Same for the C array list as well as well.
Find the Array List highest value from B and C using the previously stored sizes and append that array list in to the formatted string first.(using a loop)
Then after "+" and "\n", append the second array list to the format string.
Finally append the array list containing sum(A) into the format string.
As we added whitespaces to make all arrays the same size, the formatted string should be well formated.

Related

Java program that reads an integer value and prints the average of all odd integers between 0 and the input value, inclusive

Here is the entire question:
"Write a program that reads an integer value and prints the average of all odd integers between 0 and the input value, inclusive. Print an error message if the input value is less than 0. Prompt accordingly."
I can't seem to figure out how to get the math to work out in the for loop. I'm having trouble setting it up so that the loop increments in odds. I've tried a million different things and nothing has worked.
public static void main(String[] args) {
int value;
int oddAvg = 0;
int count = 0;
Scanner scan = new Scanner(System.in);
System.out.print("Enter an integer: ");
value = scan.nextInt();
while (value < 0){
System.out.println("Error: Input should not be less than 0");
System.out.print("Enter an integer greater than 0: ");
value = scan.nextInt();
}
for(){
}
System.out.println("The average of odd integers between 0 and " + value + " is " + oddAvg);
}
}
A trivial approach could be to just iterate from zero to the target number and check whether each number is odd or even:
int sum = 0;
int count = 0;
for (int i = 0; i <= value; i++) {
if (i % 2 != 0) {
sum += i;
count++;
}
}
int avg = sum / count;
But this, of course, is inefficient. A slightly better approach would be to start from the first odd number, 1, and increment it by 2 in each iteration, so you'd be iterating over just the odd numbers:
double sum = 0;
int count = 0;
for (int i = 1; i <= value; i += 2) {
sum += i;
count++;
}
int avg = sum / count;
Or, if you want to really be mathematically sound, you can utilize the fact that the odd natural numbers in a given range are uniformly distributed. Since this distribution is symmetric, the average equals the mean, and you don't need a loop at all:
int start = 1;
int end = value;
if (value % 2 == 0) {
value--;
}
int avg = (end + start) / 2;
General comment:
In this specific case the average would be an int, so I used ints throughout my examples. In the general usecase, you should probably use doubles to avoid mistakes of using integer division.
Here's a solution to your problem!
public static void main(String[] args) {
int input = 25; //this is whatever value you're going up to.
int accumulator = 0; //keep track of the total sum
for (int i = 0; i < input; i++) {
if (i % 2 == 1) { //if odd
accumulator+=i; // add to the running total sum
}
}
System.out.println(accumulator/(input/2)); //print out the total/num of numbers
}
You can try this if interested in Java 8. It is naive approach implementation.
int val = 0;
final OptionalDouble average = IntStream.rangeClosed(0, val)
.filter(n -> n % 2 != 0)
.average();
System.out.println(average);

Java - number in expanded form

I have given number and want it to return as a String in expanded form. For example
expandedForm(12); # Should return "10 + 2"
expandedForm(42); # Should return "40 + 2"
expandedForm(70304); # Should return "70000 + 300 + 4"
My function works for first and second case, but with 70304 it gives this:
70 + 00 + 300 + 000 + 4
Here's my code
import java.util.Arrays;
public static String expandedForm(int num)
{
String[] str = Integer.toString(num).split("");
String result = "";
for(int i = 0; i < str.length-1; i++) {
if(Integer.valueOf(str[i]) > 0) {
for(int j = i; j < str.length-1; j++) {
str[j] += '0';
}
}
}
result = Arrays.toString(str);
result = result.substring(1, result.length()-1).replace(",", " +");
System.out.println(result);
return result;
}
I think there's a problem with the second loop, but can't figure out why.
You should be adding '0's to str[i], not str[j]:
for(int i = 0; i < str.length-1; i++) {
if(Integer.valueOf(str[i]) > 0) {
for(int j = i; j < str.length-1; j++) {
str[i] += '0';
}
}
}
This will result in:
70000 + 0 + 300 + 0 + 4
You still have to get rid of the 0 digits.
One possible way to get rid of them:
result = result.substring(1, result.length()-1).replace(", 0","").replace(",", " +");
Now the output is
70000 + 300 + 4
Pseudocode uses integer arithmetics to extract decimal digits one-by-one (from the right one):
mul = 1 //will contain power of 10
while (num > 0):
dig = num % 10 //integer modulo retrieves the last digit
if (dig > 0): //filter out zero summands
add (dig * mul) to output //like 3 * 100 = 300
num = num / 10 //integer division removes the last decimal digit 6519 => 651
mul = mul * 10 //updates power of 10 for the next digit
You could do the same with pure math, using modulo % and integer division /, e.g. using Stream API:
int n = 70304;
String res = IntStream
.iterate(1, k -> n / k > 0, k -> k * 10) // divisors
.map(k -> (n % (k*10) / k ) * k) // get 1s, 10s, 100s, etc.
.filter(x -> x > 0) // throw out zeros
.mapToObj(Integer::toString) // convert to string
.collect(Collectors.joining(" + ")); // join with '+'
System.out.println(res); // 4 + 300 + 70000
There are many variations possible. If the usage of a list is allowed:
public static String expandedForm(int num){
String[] str = Integer.toString(num).split("");
String result;
List<String> l = new ArrayList<String>();
for(int i = 0; i < str.length; i++){
if(Integer.valueOf(str[i]) > 0){
String s = str[i];
for(int j = i; j < str.length - 1; j++){
s += '0';
}
l.add(s);
}
}
result = l.toString();
result = result.substring(1, result.length() - 1).replace(",", " +");
System.out.println(result);
return result;
}
One could also work directly on result:
public static String expandedForm2(int num){
String[] str = Integer.toString(num).split("");
String result = "";
for(int i = 0; i < str.length; i++){
if(Integer.valueOf(str[i]) > 0){
result += str[i];
for(int j = i; j < str.length - 1; j++){
result += '0';
}
result += " + ";
}
}
result = result.substring(0, result.length() - 3);
System.out.println(result);
return result;
}
This is also possible to do recursively. Here an example implementation:
String g(int n, int depth){ // Recursive method with 2 int parameters & String return-type
int remainder = n % depth; // The current recursive remainder
if(depth < n){ // If we aren't done with the number yet:
int nextDepth = depth * 10; // Go to the next depth (of the power of 10)
int nextN = n - remainder; // Remove the remainder from the input `n`
// Do a recursive call with these next `n` and `depth`
String resultRecursiveCall = g(nextN, nextDepth);
if(remainder != 0){ // If the remainder was not 0:
// Append a " + " and this remainder to the result
resultRecursiveCall += " + " + remainder;
}
return resultRecursiveCall; // And return the result
} else{ // Else:
return Integer.toString(n); // Simply return input `n` as result
}
}
String f(int n){ // Second method so we can accept just integer `n`
return g(n, 1); // Which will call the recursive call with parameters `n` and 1
}
The second method is so we can call the method with just a single input n. For example:
String result = f(70304);
Which will result in the String 70000 + 300 + 4.
Try it online.
To explain a bit more in depth of what this recursive method does, let's just do a step-by-step for the input 70304:
In the first recursive iteration: n=70304, depth=1, remainder=70304%1 = 0.
Since depth < n is truthy, it will do a recursive call with 70304-0 and 1*10
And since remainder is 0, it will append nothing more to the result
In the second recursive iteration: n=70304, depth=10, remainder=70304%10 = 4.
Since depth < n is still truthy, it will do a recursive call with 70304-4 and 10*10
And since remainder is 4, it will append a " + " and this 4 to the result
In the third recursive iteration: n=70300, depth=100, remainder=70300%100 = 0.
Since depth < n is still truthy, it will do a recursive call with 70300-0 and 100*10
And since remainder is 0, it will append nothing more to the result
In the fourth recursive iteration: n=70300, depth=1000, remainder=70300%1000 = 300.
Since depth < n is still truthy, it will do a recursive call with 70300-300 and 1000*10
And since remainder is 300, it will append a " + " and this 300 to the result
In the fifth recursive iteration: n=70000, depth=10000, remainder=70000%10000 = 0.
Since depth < n is still truthy, it will do a recursive call with 70000-0 and 10000*10
And since remainder is 0, it will append nothing more to the result
In the sixth recursive iteration: n=70000, depth=100000, remainder=70000%100000 = 70000.
Since now depth < n is falsey, it won't do any more recursive calls, but instead return the current n (which is 70000).
And since these were all recursive calls, we should actually look at it backwards for the result, so it will result in 70000 + 300 + 4.
So in general:
The depth < n if-check is to see when we are done with the recursive calls.
The g(n-remainder, depth*10) will remove the digits we've already output in a previous recursive iteration, and goes to the next 10k power in the next recursive iteration
The remainder != 0 if-check determines if the number we want to append was not a 0
public class Kata
{
public static String expandedForm(int num)
{
String outs = "";
for (int i = 10; i < num; i *= 10) {
int rem = num % i;
outs = (rem > 0) ? " + " + rem + outs : outs;
num -= rem;
}
outs = num + outs;
return outs;
}
}
package backup;
import java.util.Arrays;
public class FileOutput {
public static void main(String[] args){
String expForm = expandedForm(70304);
//System.out.println(expForm);
}
public static String expandedForm(int num)
{
String[] str = Integer.toString(num).split("");
String result = "";
for(int i = 0; i < str.length-1; i++) {
if(Integer.valueOf(str[i]) > 0) {
for(int j = i; j < str.length-1; j++) {
str[i] += '0';
}
}
}
result = Arrays.toString(str);
result = result.substring(1, result.length()-1).replace(",", " +");
System.out.println(result);
return result;
}
}
Output : 70000 + 0 + 300 + 0 + 4
Solution in most inner loop you need to add '0' to str[i] : str[i] += '0';
Then you need to replace "+ 0" from the resulted output.
for(int i = 0; i < str.length; i++) {
if(Integer.valueOf(str[i]) > 0) {
for(int j = 0; j < str.length - i - 1; j++) {
str[i] += '0';
}
}
}
I think the challenge of this problem is omitting 0(zero) and extra +(plus) while iterating throughout the number. String concat function can be used with condition as bellow:
public static String expandedForm(int num) {
String st = String.valueOf(num);
String finalResult = "";
for (int i = 0; i < st.length(); i++) {
String s = String.valueOf(st.charAt(i));
if (Integer.valueOf(s) > 0) {
for (int j = i; j < st.length() - 1; j++) {
s = s.concat("0");
}
if (i == st.length() - 1) {
finalResult = finalResult.concat(s);
} else {
finalResult = finalResult.concat(s + " + ");
}
}
}
return finalResult;
}
public static String expandedForm(int num)
{
String[] str = Integer.toString(num).split("");
String result = "";
String st="";
for(int i = 0; i < str.length-1; i++) {
if(Integer.valueOf(str[i]) > 0) {
for(int j = i; j < str.length-1; j++) {
str[i] += '0';
}
}
}
for(String s:str) {
st += s+" ";
}
result=st;
result = result.substring(0, result.length()-1).replace(" 0","").replace(" ", " + ");
System.out.println(result);
return result;
}
public static String expandedForm(int num)
{
int numberOfDigits =(int) Math.floor(Math.log10(num)+1);
String result="";
while(numberOfDigits-->0){
int divisor = (int)Math.pow(10,numberOfDigits);
int quotient = num/divisor;
num%=divisor;
int value = quotient * divisor;
if(value!=0)
result+=value+(numberOfDigits != 0 ?"+":"");
}
return result;
}
Try with this.
Find number of digits and iterate for every single digit.
Make a divisor of 10 power (number of digits -1) and divide the number to get quotient.
Take reminder for next iteration.
Multiply quotient and divisor and store in result if it value is not zero.
Simple Javascript Expanded Form of a number
Asked in interviews for beginners/Juniors
function expandedForm(n){
let temp = n;
let count=0;
while(temp>0){
console.log(((temp%10)*(10**count)));
count++;
temp = Math.floor(temp/10);
}
}
output will be like this:-
7
80
400
5000
10000

How do I make the final output of this code indent every ten numbers?

This code is designed to list off the prime numbers between a minimum and maximum input by the user. When the numbers are output at the end of the code, they are all on the same line. I would like there to be ten numbers per line, so I assume that it takes a loop of some kind to indent every ten numbers, however I don't know how to do this. While I have the code posted here, other, unrelated feedback would be helpful.
String primenumbers = "";
System.out.println("Prime Number Generator.");
System.out.print("Minimum: ");
int oldmin = s.nextInt();
s.nextLine();
int min = oldmin;
System.out.print("Maximum: ");
int max = s.nextInt();
s.nextLine();
System.out.println();
for (min = min; min <= max; min++)
{
int counter=0;
int num = min;
for(num = min; num >= 1; num--)
{
if(min % num == 0)
{
counter = counter + 1;
}
}
if (counter == 2)
{
primenumbers = primenumbers +min+ " ";
}
}
System.out.println("Primes Between "+oldmin+" & "+max+":");
System.out.print(primenumbers);
Instead of concatinating prime numbers into a string, you can add them into a list and iterate the list in the end, e.g.:
primenumbers = primenumbers +min+ " "; will be replaced with
List<Integer> primenumbers = new ArrayList<>();
primenumbers.add(min);
After System.out.println("Primes Between "+oldmin+" & "+max+":"); statement, you can do the following:
for(int i=0 ; i < primenumbers.size() ; i++){
System.out.print(primenumbers.get(i) + " ");
if(i+1 % 10 == 0){
System.out.println();
}
}

How to sum array contents with their powers of 3

I need to do something like this - user types in a number (e.g. 5) and the program shows the result of the following action: 1*1*1 + 2*2*2 + 3*3*3 + 4*4*4 + 5*5*5.
My code is following:
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter your number:");
int n = input.nextInt();
int a[] = new int[n];
int power = 0;
int sum = 0;
for (int i = 1; i <= a.length; i++)
{
power = (int) pow(i, 3);
// Maybe here'a the problem, a[n] has not enough space for the power (???)
sum += a[power];
}
System.out.println(Result: " + sum);
}
I think that I understand why this code doesn't work but I will appreciate any ideas about how to do it properly and runnable.
sum += power;, no need for a.
Or simply use math :
int n = input.nextInt();
int result = (int)(0.25 * Math.pow(n, 2)*Math.pow(1+n,2));
Or even more simple, as #ajb said :
int result = n*n*(n+1)*(n+1)/4;
Change:
sum += a[power];
to
a[i-1] = power;
sum += a[i-1];
or forget the array altogether
sum += power;
sum += a[power]; doesn't exist.
You need to :
store the power value in the ith array item.
add the ith array value to the sum
Change your loop body to:
power = (int) pow(i, 3);
a[i - 1] = power;
sum += a[i - 1];
You're doing way too much work.
Scanner input = new Scanner(System.in);
System.out.println("Enter your number:");
int n = input.nextInt(),
sum = 1;
for (int i=2; i<=n; i++) {
sum += (int) Math.pow(i,3);
}
done. sum now contains the sum 1³ + 2³ + 3³ + ...
Or, more efficiently with exactly the same functionality:
Scanner input = new Scanner(System.in);
System.out.println("Enter your number:");
int n = input.nextInt(),
sum = 1;
while(n > 1) {
sum += (int) Math.pow(n--,3);
}
Why? Because 1 + 5³ + 4³ + 3³ + 2³ is the same as 1³ + 2³ + 3³ + 4³ + 5³
Of course you could also just directly compute that value, using actual maths, cutting all the entire algorithm with a simple arithmetic oneliner.

Reverse Number in Java using Array

So, I'm supposed to write a program determining Ermips. I've got the rest figured out, but I'm not sure how to reverse the number correctly. I'm supposed to use an array to reverse it.
For example, the number 357.
I use the mod operator to take the last digit and put it in the first index of the array.
357%10 = 7
myArray[0] = 7
357/10 = 35 for a remainder
Use the remainder 35 to start over.
35%10 = 3
myArray[1] = 3
35/10 = 3 for a remainder
etc. ...
I need to basically loop this so I can do any length number to reverse it.
Then, after I have that array, display the array to produce the number in reverse....753.
public class Reverse {
public static void main(String[]args) {
int n = 357;
int MAX_NUMBERS = 20;
int currentNumber = 0;
int reverseNumber = 0;
int remain = 0;
int sum = 0;
int [] holdDigits = new int [MAX_NUMBERS];
int exp = holdDigits.length;
System.out.println("exp: " + exp);
int index = 0;
//sum array
int count = holdDigits.length;
while (count > 0){
holdDigits[index] = n%10;
System.out.println(index + "index: " + holdDigits[index]);
n = n/10;
System.out.println("remainder: " + n);
count--;
index++;
}
while (index < holdDigits.length){
reverseNumber += holdDigits[index]*Math.pow(10,count-exp);
index--;
System.out.println("sum so far: " + sum);
}
System.out.println("Number reversed: " + reverseNumber);
}//end of main
}//end of class
Totally figured it out now, thanks to Yogendra Singh !
Check it out:
public class Reverse2 {
public static void main(String[]args) {
int n = 76495;
int MAX_NUMBERS = 20;
int reverseNumber = 0;
int index = 0;
//declare an array to hold the digits while reversing
int [] holdDigits = new int [MAX_NUMBERS];
//the exponent is the number of spaced used in the array
int exp = holdDigits.length;
//while the number is greater than 0, use mod to put the right-most
//digit in index 0, divide the remaining number and increase the index
//to put it in the next open slot of the array.
while (n > 0){
holdDigits[index] = n%10;
n = n/10;
index++;
}
//decrease the index by one so it doesn't add the remaining zero as
//a placeholder in the number
index--;
//count is the index because below, you subtract it, making the display
//of the array reversed.
int count= index;
//while the index is greater than zero, by starting at the last filled
//slot of the array, the reverse number is added onto each time by
//multiplying the number times 10 to the power of whichever place it
//is which happens to be the index.
//EXAMPLE: to turn 7 into 700, multiply by 7x10^3
while (index >= 0 ){
reverseNumber += holdDigits[count-index]*Math.pow(10,index);
//lower the index to do the next number of the array
index--;
}
System.out.println("Reversed number: " + reverseNumber);
}//end of main
}//end of class
There are some issues in the code as below:
Run the first loop until remainder of division is 0
Count the digits found in the division process
Reduce the index by 1 after first loop as it is post incremented by one in the while loop
Sample corrected code could be as below:
int exp = holdDigits.length;
System.out.println("exp: " + exp);
int index = 0;
while (n > 0){
holdDigits[index] = n%10;
System.out.println(index + "index: " + holdDigits[index]);
n = n/10;
System.out.println("remainder: " + n);
index++;
}
index--;
int count= index;
while (index >=0 ){
reverseNumber += holdDigits[count-index]*Math.pow(10,index);
index--;
System.out.println("sum so far: " + sum);
}
i apology if already you have got an answer but this is an short way to get reverse number using array with for loop.
var val = prompt("enter number");
var New = val.split("");
var arr1 = [];
console.log(New);
for (i = New.length - 1; i >= 0; i--) {
arr1 += New[i] + ',';
} console.log(arr1);

Categories