This program is supposed to print the numbers (indiviual digits) in a number
`
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter a number");
int number = sc.nextInt();
int Size = 0;
String Conversion = Integer.toString(number);
Size = Conversion.length();
int n = 0;
while (n <= Size){
int d = number%10;
int power = Size - 2;
number = (number/(10^(power)));
System.out.println(d);
n += 1;
}
}
}
`
Really Appreciate for Anyone for Took time to help me.
Thanks
For some reason I get
1
9
3.
instead of
1
3
4
using the debugger gives me some hint, Specifically this block `
number = (number/(10^(power)));
`
for second iteration the value is +4 than expected, 3.
for third Its okay.
changing and adding +4 on that block gives
1
3
7
4
Found it !!
Credit OH GOD SPIDERS, tkausl
Solution 1 : Instead of using carrot characters in
number = (number/(10^(power)));
use Math.pow function.
Solution 2 :
Don't use (number/(10^(power))
instead just divide by 10
Related
I've written code to print the digits of an integer on separate lines, but I am not getting the expected output. The output of the code is instead in reverse order. How can I make my output correct without using the Math.pow method?
import java.util.Scanner;
class NumberInDigit
{
public static void main(String[] args)
{
int div;
Scanner sc = new Scanner(System.in);
System.out.println("enter the number");
int n = sc.nextInt();
while(n>0)
{
div = n%10;
n= n/10;
}
System.out.println(div);
}
}
n = 234
Output is 4,3,2
Expected output is 2,3,4
The "%" is the modulo operator so div = n%10; takes n (234), then finds the remainder the 234 when divided by 10. 234/10 = 23.4 (i.e. 4 is the remainder). So div is assigned a value of 4 (i.e. div = 4). Then you are dividing n (234), by 10 and reassigning it to n - so (234 / 10 = 23), note the remainder is ignored.
That is the end of the first iteration of the loop, and it returns div = 4.
The second iteration (when n = 23) will print out 3 (because 23 / 10 = 2r3) - remember we are returning the remainders. N is then set to 2.
The third itereration (when n = 2) will print out 2 (because 2/10 = 0r2) - the remainder is 2. N is now set to 0 as (2 / 10 = 0). So then next iteration will fail the condition of n > 0.
This is why you are getting 4,3,2.
There are a number of ways to get the expected number, but since you are working in base10 (i.e. the decimal system), I think the easiest would be just to convert the number into a string and then iterate through the string printing every number until you reached the end, or a decimal point.
you are dividing division Remainders and again dividing them again, if you want to operation on string use array
You can do it this way also:
int n=234,x=n,y=100;
while(x>=0)
{
x=n/y;
n=n%y;
System.out.println(x);
y=y/10;
}
This way output is 2,3,4.
First of all your code has syntax and logical issues. "n" doesn't have a type and it should only return 4 (since you are executing return it should not continue the while loop).
To accomplish what you need you can change your code a bit:
public static void main(String [] args){
System.out.println(printReversedNumList(234));
}
private static List printReversedNumList(int num) {
final List<Integer> reversedNumList = new ArrayList<>();
while(num>0)
{
int remainder = num%10;
num= num/10;
reversedNumList.add(remainder);
}
Collections.reverse(reversedNumList);
return reversedNumList;
}
so I have this problem where finding the percentage doesn't work and I really don't know why,so my assignment is to find the number of candidates for election and the number of electors and at the end it should show the percentage of the votes example if there are 3 candidates and 6 electors and 1st candidate gets 3 votes,2nd gets 2 votes, and the 3rd gets 1 vote, it should show : 50.00%,33.33%,16.67%.
Below is my code, it gets right the number of votes but when it comes to percentage it just shows 0.0% in all cases.I hope you guys can help me out.
import java.util.Scanner;
public class ElectionPercentage {
public static void main(String[]args){
//https://acm.timus.ru/problem.aspx?space=1&num=1263
Scanner sc = new Scanner(System.in);
System.out.println("Enter how many candidates are : ");
int candidates = sc.nextInt();
int [] allCandidates = new int[candidates];
int startingCandidate = 1;
for(int i = 0; i < candidates;i++){
allCandidates[i] = startingCandidate++; //now value of the first element will be 1 and so on.
}
//for testing System.out.println(Arrays.toString(allCandidates));
System.out.println("enter the number of electors : ");
int electors = sc.nextInt();
int [] allVotes = new int[electors];
for(int i =0;i < electors;i++){
System.out.println("for which candidate has the elector voted for :");
int vote = sc.nextInt();
allVotes[i] = vote; //storing all electors in array
}
System.out.println();
int countVotes = 0;
double percentage;
for(int i = 0;i<allCandidates.length;i++){
for(int k = 0; k < allVotes.length;k++){
if(allCandidates[i]==allVotes[k]){
countVotes++;
}
}
System.out.println("Candidate "+allCandidates[i]+" has : "+countVotes+" votes.");
percentage = ((double)(countVotes/6)*100);
System.out.println(percentage+"%");
countVotes = 0;
}
}
}
countVotes is an int 6 is also an int. Thus, (countVotes/6) which is in your code, near the end, is integer division. 11/6 in integer division is 1. 5/6 is 0. It rounds by lopping off all decimals. That's probably not what you want, especially because you try to cast it to double afterwards.
You're casting the wrong thing. But you don't even need the cast at all; if either side is double, the whole thing becomes double division. So, instead of: percentage = ((double)(countVotes/6)*100); try percentage = 100.0 * countVotes / 6.0;
Also, presumably, that 6 should really be a variable that counts total # of votes, no? i.e. electors, so: percentage = 100.0 * countVotes / electors;
The fact that we kick off the math with 100.0 means it'll be double math all the way down.
countVotes is an int. When you do (double)(countVotes/6), (countVotes/6) happens first. This evaluates to 0 since both are int. To fix this, change 6 to 6.0.
(double)(countVotes/6.0)*100
In which case, the cast to double is no longer needed.
(countVotes/6.0)*100
Question:
The Utopian tree goes through 2 cycles of growth every year. The first growth cycle occurs during the spring, when it doubles in height. The second growth cycle occurs during the summer, when its height increases by 1 meter.
Now, a new Utopian tree sapling is planted at the onset of the spring. Its height is 1 meter. Can you find the height of the tree after N growth cycles?
Input Format
The first line contains an integer, T, the number of test cases.
T lines follow. Each line contains an integer, N, that denotes the number of cycles for that test case.
Constraints
1 <= T <= 10
0 <= N <= 60
Output Format
For each test case, print the height of the Utopian tree after N cycles.
//FINALLY, HOPE so .. WHAT QUESTION IS SAYING..
INITIALLY VALUE IS 1 .. IF SPRING OCCURS.. IT'S VALUE WILL BE DOUBLED.. THAT MEANS .. IT WILL BE MULTIPLIED BY 2.. BUT IF SUMMER OCCUR IT'S VALUE WILL BE ADDED BY 1...
If i give input:
2 //here 2 is the number of question..
0
1
So, Output must be:
1
2
Another example,
sample of output:
2
3
4
So, Sample of input will be:
6
7
HOPE SO.. YOU UNDERSTAND WHAT QUESTION IS ASKING, HERE NOW WE HAVE TO MAKE A PROGRAM INTO JAVA....
Okay as further i made a program for this..
package com.logical03;
import java.util.Scanner;
public class MainProgram{
public static void main(String[] args){
int num=1;
int[] array=new int[100];
Scanner in=new Scanner(System.in);
System.out.println("Enter the number of Questions: ");
int n_Elements=in.nextInt();
System.out.println("Enter the values now: ");
for(int i=1; i<=n_Elements; i++){
array[i]=in.nextInt();
}
for(int i=1; i<=n_Elements; i++){
if(array[i]==0){
System.out.println("\n1");
}
else{
for(int j=1; j<=array[i]; j++){
if(j%2!=0){
num=num*2;
}
else{
num=num+1;
}
}
System.out.println(num);
}
}
}
}
As i run into here .. it adds the second number of question into my output.. Suppose..
If i give input as:
2
3
4
So, output must suppose to be:
6
7
Which is correct!!
But My program gives the output as:
6
27 //which is incorrect..becoz it adds the sum of above number :(
Mistake - int num = 1; should be declared in inside parent loop to refresh it's value.
public static void main(String[] args) {
int[] array = new int[100];
Scanner in = new Scanner(System.in);
System.out.println("Enter the number of Questions: ");
int n_Elements = in.nextInt();
System.out.println("Enter the values now: ");
for (int i = 1 ; i <= n_Elements ; i++) {
array[i] = in.nextInt();
}
for (int i = 1 ; i <= n_Elements ; i++) {
int num = 1;
if (array[i] == 0) {
System.out.println("\n1");
} else {
for (int j = 1 ; j <= array[i] ; j++) {
if (j % 2 != 0) {
num = num * 2;
} else {
num = num + 1;
}
}
System.out.println(num);
}
}
}
Output
Enter the number of Questions:
2
Enter the values now:
3
4
6
7
My approach is to take on account that first cycle (2 * height) occurs on odds indexes, and second cicle (1 + height) occurs on even indexes, from 1 to n (inclusive), starting index 0 is always 1.
return IntStream.rangeClosed(1, n)
.reduce(1, (acc, idx) -> idx % 2 != 0 ? acc * 2 : acc + 1);
This is my first contribution, only learning to code and solve algorithms, I had to find a workable solution with simple to follow code credit to http://www.javainterview.net/HackerRank/utopian-tree
import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
public class Solution {
public static void main(String[] args) {
//receive input
Scanner in = new Scanner(System.in);
//no of test cases
int T=in.nextInt();
//no of cycles
int[] N = new int[T];
for(int i=0;i<T;i++){
N[i]=in.nextInt();
}
int height=1;
for(int i=0;i<N.length;i++){
height=1;
for(int j=1;j<=N[i];j++){
if((j%2) ==1)
height=height*2;
else
height++;
}
System.out.println(height);
}
}
}//this the end of the class
I'm stuck with this problem of the UVA as I can't figure out why my solution is not good.
As long as I understand, the question is to get the integer square root of any given number from 1 to 10^1000. So my intention was to flip the bits of a BigInteger from position i/2, where i is the number of bits in the minimal two's-complement representation of the input and decrease the i value each time the square of my guess is still less than the input.
Notice that every input I've tried so far is getting the expected result!
The example for, lets say, sqrt(36) would be:
36 -> 100100
bitCount = 2 ( (6 - 1)/2 = 2)
guess = 100 (4)
(4 * 4 = 16 < 36) -> bitCount = 1;
guess = 110 (6)
(6 * 6 = 36 = 36) -> break;
So the solution to sqrt(36) is 6, awesome... This way the solution to sqrt(37), sqrt(38), sqrt(39), until sqrt(49) would be 6 too.
Maybe the code is more explanatory.
import java.math.BigInteger;
import java.util.Scanner;
public class Main{
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
BigInteger bi;
for(int i = n; i != 0; i--){
bi = new BigInteger(in.next());
System.out.println(squareRoot(bi));
}
in.close();
}
private static BigInteger squareRoot(BigInteger N) {
int bitCount = (N.bitLength() - 1)/2;
int aux = 0;
BigInteger guess = BigInteger.ZERO;
while(bitCount >= 0){
guess = guess.flipBit(bitCount);
aux = guess.multiply(guess).compareTo(N);
if(aux < 0)
bitCount--;
else if(aux != 0){
guess = guess.flipBit(bitCount);
bitCount--;
}
else{
break;
}
}
return guess;
}
}
For sure it is not the best performance solution and it seems to be wrong, but could someone explain me the reason why it is wrong?
Thank you guys!
From the problem statement:
The Output
For each test case, your program should print X in the same format as Y was given in input.
Print a blank line between the outputs for two consecutive test cases.
I got an accepted submission by modifying your program to take this into account.
However, I would suggest binary search as a simpler approach (but the problem doesn't seem relly well defined since the number of test cases is not given, I think).
Good morning, I am on now to lesson 4 and am having a bit of trouble using loops. Please note that I have seen it resolved using strings but I am trying to grasp loops.
The reason for the trouble is I need to show both answers: The integer broken into individual number ex: 567 = 5 6 7
And then 567 = 18
I am able to get the integer added together but am not sure on how to separate the integer first and then add the individual numbers together. I am thinking that I need to divide down to get to 0. For instance if its a 5 digit number /10000, /1000, /100, /10, /1
But what if the user wants to do a 6 or 7 or even a 8 digit number?
Also I am assuming this would have to be first and then the addition of the individual integers would take place?
thanks for the guidance:
import java.util.Scanner;
public class spacing {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n;
System.out.print("Enter a your number: ");
n = in.nextInt();
int sum = 0;
while (n != 0) {
sum += n % 10;
n /= 10;
}
System.out.println("Sum: " + sum);
}
}
Since this is a lesson, I won't give you the solution outright, but I will give you some hints:
You're only thinking in int. Think in String instead. :) This will also take care of the case where users provide you numbers with a large number of digits.
You will need to validate your input though; what if someone enters "12abc3"?
String.charAt(int) will be helpful.
Integer.parseInt(String) will also be helpful.
You could also look at using long instead of int; long has an upper limit of 9,223,372,036,854,775,807 though.
//I assume that the input is a string which contains only digits
public static int parseString(String input)
{
char[] charArray = input.toCharArray();
int sum = 0;
for (int index = 0; index < input.length; index++)
{
sum += Integer.parseInt(charArray[index] + "");
}
return sum;
}
Use the function above, pass your input to the function and use the output as you like.