import java.text.BreakIterator;
import java.util.*;
public class Main {
public static void main(String args[]) {
Scanner in= new Scanner(System.in);
System.out.println("nomber");
int n= in.nextInt();
int s= n*n;
int l = (""+s).length();
System.out.println(l);
}
}
how can I extract last digit from input in a simple way. Not so complicated like while loop.... java
Since last digit is also the remainder of dividing by 10, you can use n % 10.
The simplest way to extract last digit is modulo to 10. Example: 123 % 10 = 3
After that, if you want to continue to extract last digit (it's 2 in this case), you should assign number = number /10 that will return the remain of the number.
// Example n = 123
int lastDigit_1 = n % 10; // This will return 3
n = n /10 // This will return 12 because 123 / 10 = 12
int lastDigit2 = n % 10; // This will return 2
n = n /10 // This will return 1
int lastDigit3 = n % 10;
...
To implement the above concept, u should try using while loop for better approach.
Using while:
while(n != 0){
someVariable = n % 10;
// YOUR LOGIC HERE
n = n / 10;
}
Related
You have to print a pattern using recursion. Given a input
N
the pattern looks like this
N
,
a
i
,
a
i
+
1
,
a
i
+
2
,.....,
N
. Where if
a
i
>
0
then
a
i
+
1
=
a
i
−
5
else
a
i
+
1
=
a
i
+
5
. It will be a decreasing sequence from
N
till
a
i
<=
0
and then an increasing sequence till
N
. (See sample test cases for better explanation)
Input format
First line contains an integer
T
denoting number of test cases.
For each of the next
T
lines, each line contains an integer
N
.
Output format
For each test case on a new line, print the required pattern.
Constraints
1
<=
T
<=
6
0
<=
N
<=
2000
Example
Input
2
16
10
Output
16 11 6 1 -4 1 6 11 16
10 5 0 5 10
Sample test case explanation
For the first test case
N=16, it will be a decreasing sequence till the printing number becomes <=0.
16 11 6 1 −4
After this point it will be a increasing sequence till the printing number becomes N
1 6 11 16
So the pattern is 16 11 6 1 −4 1 6 11 16.
My code is below but i got the output as 16,11,6,1,-4 only. Help me to correct this code
import java.util.Scanner;
public class Day3
{
public static void series(int n,boolean b)
{
int temp = n;
boolean flag=b;
System.out.println(temp+" ");
if(flag==true)
temp-=5;
else if(flag==false)
temp+=5;
if(temp<=0)
flag=false;
if(temp<=n)
series(temp,flag);
}
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
int t = sc.nextInt();
while(t>0)
{
int n = sc.nextInt();
series(n,true);
t-=1;
}
}
}
Because 'n' changes in every cases. You must create another variable and keep first 'n' in that, for control if temp smaller than 'n'.
For example
import java.util.Scanner;
public class Day3
{
int firstN = 0; //added that line
public static void series(int n,boolean b)
{
int temp = n;
boolean flag=b;
System.out.println(temp+" ");
if(flag==true)
temp-=5;
else if(flag==false)
temp+=5;
if(temp<=0)
flag=false;
if(temp<=firstN) //changed that line
series(temp,flag);
}
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
int t = sc.nextInt();
while(t>0)
{
int n = sc.nextInt();
firstN = n; //added that line
series(n,true);
t-=1;
}
}
}
Also a little tip;
you can use (flag) for (flag==true)
and (!flag) for (flag==false)
Just FYI : Although this can be solved using recursion, it can be solved more efficiently without using recursion. It is as simple as this:
private static void printSeries(int N) {
int T = N;
while ( T >= 0 ) {
System.out.print(T + " ");
T = T - 5;
}
while ( T <= N ) {
System.out.print(T + " ");
T = T + 5;
}
}
I have been tasked with the assignment of creating a method that will take the 3 digit int input by the user and output its reverse (123 - 321). I am not allowed to convert the int to a string or I will lose points, I also am not allowed to print anywhere other than main.
public class Lab01
{
public int sumTheDigits(int num)
{
int sum = 0;
while(num > 0)
{
sum = sum + num % 10;
num = num/10;
}
return sum;
}
public int reverseTheOrder(int reverse)
{
return reverse;
}
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
Lab01 lab = new Lab01();
System.out.println("Enter a three digit number: ");
int theNum = input.nextInt();
int theSum = lab.sumTheDigits(theNum);
int theReverse = lab.reverseTheOrder(theSum);
System.out.println("The sum of the digits of " + theNum + " is " + theSum);
}
You need to use the following.
% the remainder operator
/ the division operator
* multiplication.
+ addition
Say you have a number 987
n = 987
r = n % 10 = 7 remainder when dividing by 10
n = n/10 = 98 integer division
Now repeat with n until n = 0, keeping track of r.
Once you understand this you can experiment (perhaps on paper first) to see how
to put them back in reverse order (using the last two operators). But remember that numbers ending in 0 like 980 will become 89 since leading 0's are dropped.
You can use below method to calculate reverse of a number.
public int reverseTheOrder(int reverse){
int result = 0;
while(reverse != 0){
int rem = reverse%10;
result = (result *10) + rem;
reverse /= 10;
}
return result;
}
package test;
import java.util.Scanner;
public class SplitNumber
{
public static void main(String[] args)
{
int num, temp, factor = 1;
Scanner sc = new Scanner(System.in);
System.out.println("Enter a number: ");
num = sc.nextInt();
temp = num;
while (temp != 0) {
temp = temp / 10;
factor = factor * 10;
}
System.out.print("Each digits of given number are: ");
while (factor > 1) {
factor = factor / 10;
System.out.print((num / factor) + " ");
num = num % factor;
}
}
}
I can't understand this int factor's job. Can someone help me to understand this codes algorithm?
In programming languages, if you hold double value in the int,it rounds the number to lower one thus if you do 15/10 it will return 1 as int and if you do 5/10 it will return 0. With this knowledge you can understand.
For example,let the number be 953,
while (temp != 0) {
temp = temp / 10;
factor = factor * 10;
}
1.Iteration temp = 95 , factor = 10
2.Iteration temp = 9 , factor = 100
3.Iteration temp = 0 , factor = 1000
end of while loop because temp is 0.
while (factor > 1) {
factor = factor / 10;
System.out.print((num / factor) + " ");
num = num % factor;
}
1.Iteration num = 953 factor = 100 , 953/100 = 9 (you get first digit)
2.Iteration num = 953%100 = 53 , factor = 10 , 53/10 = 5 (you get second digit)
3.Iteration num = 53%10 = 3 , factor = 1 , 3/1 = 3 (you get last digit)
End of while loop.
Actually it is basic math. When you want to extract nth digit of number, you just have to divide it by 10^n.
The modulus operator to extract the rightmost digit or digits from a number. For example, x % 10 yields the rightmost digit of x (in base 10). Similarly x % 100 yields the last two digits.
Here more info
If you would not care about flipping the order of digits, you could simply write
int num = sc.nextInt();
do {
System.out.println(num % 10);
num = num / 10;
} while(num != 0);
The modulo operation num % 10 calculates the remainder of dividing num by 10, effectively gets the digit at the lowest position ("ones"). 0 % 10 is 0 ... 9 % 10 is 9, 10 % 10 is 0 again, and so on. Then the division by 10 makes the old "tens" the new "ones", and the entire thing is repeated until 0 remains.
The hassle in your code is about emitting the digits in the "correct" order, highest position first, ones last. So it first checks how many digits are in your number, factor grows to the same size in the process. temp=temp/10; has the same role as num=num/10; in the short snippet (cutting a digit from the number in each iteration), and factor=factor*10 "adds" a digit to factor at the same time. [I just stop here as there is an accepted answer already explaining this]
I'm trying to get a for loop to start on the last digit of an integer that is given by the user through scanner. Any suggestions?
for(int i = number.length()-1;...)
I'm looking for something along those lines but that won't leave me with a compile error
You must convert the number to a String then iterate through each character.
public class IterateNumber {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Please enter a number:");
String num = String.valueOf(scanner.nextInt());
for(int i = num.length()-1; i >= 0; i--){
System.out.println(num.charAt(i));
}
}
}
Use integer arithmetic:
for (int i = number, digit = i % 10; i > 0; i = i / 10, digit = i % 10) {
// do something with "digit", which will iterate from last digit to first
}
Here's some sample code showing it working:
int number = 1234567890;
for (int i = number, digit = i % 10; i > 0; i = i / 10, digit = i % 10) {
System.out.println(digit);
}
Output:
0
9
8
7
6
5
4
3
2
1
The homework problem is the user enters a number. Then you have to write a program that reverses that order. So if the user enters 7364 you have to write a program that presents 4637 on the next line. I think I've figured out the solution but I'm not sure how to write it.
Since the last number is the first number in reverse order that means that if someone enters 7364 that means i want to get 4637. I have to write a program that multiplies 4 by 1000, 6 by 100, 3 by 10 and 7 by 1 then add those up to get 4637. I'm not not 100% sure how to do it. What's messing me up is how to multiply one number by 1000, the next by 100, the next by 10 and the next by 1 then add those up.
import acm.program.*;
public class ReverseNumber extends ConsoleProgram{
public void run(){
int n = readInt("please enter any positive number: ");
int total = 0;
while ( n > 0){
total = total + n % 10; <----?
n = n * 1000; <----?
}
println("the reverse order is" + total);
}
}
The easiest way to do it using library.
System.out.println(new StringBuilder(String.valueOf(i)).reverse());
Try this:
while( n != 0 )
{
reverse = reverse * 10;
reverse = reverse + n%10;
n = n/10;
}
Logic is to get a single digit in each iteration starting from unit place, until all digits are encountered.
n is the input no.
reverse is the variable where reverse of n is stored after while is finished.
% operator when used with 10, gives you the digit at unit place.
/ operator when used with 10, goves you all the digits except the digit at unit place.
When n = 7364 and reverse = 0
in 1st iteration, loop will look like:
while(7364 != 0) // true
{
reverse = 0 * 10; // reverse = 0
reverse = 0 + 7364%10 // reverse = 4
n = 7364/10 // n = 736
}
in 2nd iteration:
while(736 != 0) // true
{
reverse = 4 * 10; // reverse = 40
reverse = 40 + 736%10 // reverse = 46
n = 736/10 // n = 73
}
in 3rd iteration:
while(73 != 0) // true
{
reverse = 46 * 10; // reverse = 460
reverse = 460 + 73%10 // reverse = 463
n = 73/10 // n = 7
}
in 4th iteration:
while(7 != 0) // true
{
reverse = 463 * 10; // reverse = 4630
reverse = 4630 + 7%10 // reverse = 4637
n = 7/10 // n = 0
}
in 5th iteration:
while(0 != 0) // false and loop ends
{
...
}
and we have reverse = 4637.
Well, to reverse the number the simplest solution would be to convert it to a string get the first letter and append it at the end until you reach the last letter or number in this case. Also, you can do pretty much the same with the multiplication part. Get the numbers one by one as a string convert it back to int then multiply and add.
EDIT: if you cant do it using strings. here is a somewhat mathematical solution.
int num = 123456; // any number than you want to reverse
string revnum = ''; // the reversed number
int temp = 0;
do {
temp= (temp*10)+(num%10);
num = (int)(num/10);
}while(num>0){
revnum = revnum + temp;
}
This should work:
total = 0;
while (n > 0) {
total = total * 10 + n % 10;
n = n / 10;
}
println("the reverse order is " + total);
You don't have to know how many digits there are in the original number, you're iterating through all of them anyway. Here's what happens:
When you get a new digit (n % 10), you multiply the result by 10 and add it to it. This way, you offset the digits in the result.
Then you eliminate the last digit (the one you added in the step before) from the original number by doing n / 10.
Do you have to represent it with an int? A String seems more natural?
If you stick with the int, you need to keep track of the factor to multiply with: which means another variable that you multiply by 10 each iteration.
Convert the Int to String, then put it in a StringBuffer
then use .reverse()
I wouldn't want to add the codes because there are many samples for this.
Like this one.
After that, you could convert it again to String.
public class value{
public static void main(String[] args){
int n=Integer.parseInt(args[0]);
int t=0;
do{
t=n%10;
System.out.print(t);
n=n/10;
}while(n>0);
}
}