i have written a program to find out the number of digit in a given number in java. Is it a good way to do it and what is the time complexity of the program:
import java.util.*;
public class Inst {
/**
* #param args
*/
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
double a = sc.nextDouble();
for(int n=0;n<200000;n++)
{
double b=Math.pow(10, n);
double d=a/b;
if(d>=0 & d<=9)
{
System.out.println("The number has "+(n+1)+" DIGITS");
break;
}
}
}
}
How about this?
double input = Input;
int length = (input + "").length();
import java.util.*;
public class JavaLength {
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
Double d = sc.nextDouble();
String dString = d.toString();
System.out.println(d);
if(dString.contains(".")){
System.out.println("Total Characters: " + (dString.length() -1 ));
}else{
System.out.println("Total Characters: " + (dString.length()));
} /*-1 for the '.' in between, if it exists!*/
}
FWIW, the most efficient way to test the number of (decimal) digits needed to represent an integer will be a tree of if / else tests. The complexity will be O(1), but the code will be UGLY (but portable); e.g.
int num = ...
if (num >= 0)
if (num < 1000000)
if (num < 10000)
if (num < 100)
if (num < 10)
return 1
else
return 2
else
...
else
...
else
...
else
...
Using pow / log is not generally a good solution, as there may be a number close to a power of ten that rounds to the next integer. In double precision one should be able to precisely store all 15 digit numbers for which log10 should be absolutely < 15. In reality log10(10^15 - 100) still rounds to 15.
One will be stuck with the same algorithms, that are internally used in decimal to string conversions:
trial division:
while (i > 0) { i=i/10; count++; }
trial multiplication:
j=10; while (i >= j) { j*=10; count++; }
trial division from msb to lsb converting to string;
j=10000000; while (i>0) {
while (i>=j) { digit++;i-=j;};
j/=10; *str++=digit+'0'; digit=0:
}
Binary to bcd conversion using double dabble algorithm where each digit is represented by reduced set of hexadecimal digits (omitting a-f).
This logic was originally written in c++, but i believe is the best way to find number of digits, store them in reverse order and find sum of digits.
int n;
int count=0, sum=0;
int j=0;
int ar[10]; //array to store digits
cin>> n; //input number
do{
if((n/10)==0){
count++;
ar[j]=n;
break;
}
else{
count++;
ar[j]= (n%10);
j++;
n=int(n/10);
}
}
`
while((n/10)!=0||(n%10)!=0);
cout<<"The number of digits is: "<<count<<"\n"<<"The reverse number is: ";
for(int u=0;u<count;u++){
cout<<ar[u];
sum+=ar[u];
}
cout<<"\n"<< "Sum of digits is: "<< sum;
}`
Related
world! :)
It is my third programming day (please, be lenient...)
Code was intended to find out whether the sum (when it reaches 1 digit only) of digits of number 123456789 can be divided by 9.
I cannot find how to make second 'else' work - any help and explanation why so would be highly appreciated:
package lesson3;
public class Task6 {
public static void main(String[] args) {
int n=123456789;
System.out.println(n);
do{
private static int sumDigits(int n)
int s=sumDigits(n);
if (s < 10) ;
{
if (s == 9) System.out.println("divides by 9");
else System.out.println("doesn't divide by 9");
break;
}
else n = s;
}while (true);
}
The function, sumDigits should return the sum of digits of the parameter, n. For this, you can add each digit of n to a variable, sum initialized with the value, 0. The value of x % 10 gives you the last digit of x. Every time you add the last digit of n to sum, divide it by 10 to make it one digit less from the end.
You need a loop to pass the sum of digits to sumDigits until the sum of digits become a single digit. I suggest you use a do-while loop which guarantees its body to be executed at least once.
At the end of the loop mentioned in point#2, you will have the sum of digits as a single digit. The final thing that you need to do now is to check if this sum is divisible by 9.
Note that if x % y == 0, then x is divisible by y.
Demo:
public class Main {
public static void main(String[] args) {
int n = 123456789;
int singleDigitSum = 0;
int divisibleBy = 9;
do {
singleDigitSum = sumDigits(n);
n = singleDigitSum;
} while (singleDigitSum > 9);
if (singleDigitSum % divisibleBy == 0) {
System.out.println("The single digit sum is divisible by " + divisibleBy);
} else {
System.out.println("The single digit sum is divisible by " + divisibleBy);
}
}
private static int sumDigits(int n) {
int sum = 0;
while (n > 0) {
sum += n % 10;
n /= 10;
}
return sum;
}
}
Output:
The single digit sum is divisible by 9
Note: Java does not allow defining a method/function inside another method/function. You have done this mistake by defining the function, sumDigits inside the method, main.
Try the code below:
package lesson3;
public class Task6 {
public static void main(String[] args) {
int number = 123456789;
int sumOfDigits = sumDigits(number);
if (sumOfDigits%9 == 0) {
System.out.println("divides by 9");
return;
}
System.out.println("doesn't divide by 9");
}
public static int sumDigits(int num)
int sum = 0;
while (num > 0) {
sum = sum + num % 10;
num = num / 10;
}
return sum;
}
I need to write a program that allows the user to enter a 13-digit ISBN as a single integer.
The program should then determine and show whether the number is valid according to the formula above. It also needs to print an error message if the user tries to enter a number longer than 13 digits.
Below is the code I am working on.
I'm new to java and I don't understand where it went wrong. I also don't seem to figure out how to get the length of a long variable.
import java.util.Scanner;
public class ISBNChecker{
public static void main(String [] args){
long isbnNumber;
long isbnTotal;
long x;
Scanner scnr = new Scanner(System.in);
isbnNumber = scnr.nextLong();
while (isbnNumber > 0) {
x = isbnNumber % 10;
isbnTotal = total + x;
isbnNumber = isbnNumber / 10;
x = isbnNumber % 10;
isbnTotal = total + (3 * x);
isbnNumber = isbnNumber / 10;
}
if (isbnTotal % 10 = 0) {
System.out.println("Number is valid!");
}
else {
System.out.println("Number is invalid.");
}
}
}
Fix your (own) current code
In your original code, you have a couple of tiny errors:
isbnTotal = total + x;
total is not declared anywhere, and isbnTotal is not initialized.
if (isbnTotal % 10 = 0) {
You need to compare with double =, a single one is for assignation, double == is for comparison.
Separate your code into modules to improve it
... determine and show whether the number is valid according to the formula above.
I think that you forgot to write the formula, but according to Wikipedia, is this one:
So, you need to check if the sum of all digits multiplied by their weight (alternating 1 and 3) is a multiple of 10.
So, first of all we need to get the sum of all digits and multiply each digit by 1 or 3 alternating (backwards as we're gonna be using the modulo operator).
So, we need something like this:
private static int getSum(long isbn) {
int count = 0;
int sum = 0;
do {
sum += count % 2 == 0 ? isbn % 10 : 3 * (isbn % 10);
count++;
isbn /= 10;
} while (isbn > 0);
return sum;
}
Let me explain what the above code does, is make use of the ternary operator (CTRL-F on the page to read about it), to determine if we need to multiply by 1 or 3, in the formula it starts with 1, so the easiest way to do it is by checking if the current index is even or odd, if even, multiply by 1, otherwise multiply by 3, and adds that number to the sum.
Then it divides the current number by 10.
Then all we have to do is check if the sum of all digits multiplied by their respective weights is a multiple of 10.
private static boolean isAValidISBN(long isbn) {
return getSum(isbn) % 10 == 0;
}
And just before that, if the given number doesn't have 13 digits, we say that it isn't.
So, in the end our program should be something like:
public class ISBNChecker {
public static void main(String[] args) {
String isbnNumber = "978030640615";
if (isbnNumber.length() != 13) {
System.out.println("ISBN Number is invalid");
return;
}
if (isAValidISBN(Long.parseLong(isbnNumber))) {
System.out.println(isbnNumber + " is a valid ISBN");
} else {
System.out.println(isbnNumber + " is not a valid ISBN");
}
}
private static int getSum(long isbn) {
int count = 0;
int sum = 0;
do {
sum += count % 2 == 0 ? isbn % 10 : 3 * (isbn % 10);
count++;
isbn /= 10;
} while (isbn > 0);
return sum;
}
private static boolean isAValidISBN(long isbn) {
return getSum(isbn) % 10 == 0;
}
}
And if we take the Wikipedia value, we get this output:
9780306406157 is a valid ISBN
I don't understand your question clearly, but I suppose what you want to do is validate if the number provided by the user has 13 digits or not, you could do this:
public static void main(String[] args) {
String userNumber;
Scanner scnr = new Scanner(System.in);
System.out.println("Enter ISBN number, 13 digit");
userNumber = scnr.nextLine();
/*regular expression to verify that it contains only 13 digits*/
if(userNumber.matches("^[0-9]{13}$")) {
System.out.println("Number is valid");
} else {
System.out.println("Number is invalid");
}
}
First of all, what do you mean with:
according to the formula above.
What formula do you mean? And Second, to get the length of an long or integer just do:
int length = ("" + isbnNumber).length()
And btw, when you are doing an if statement do "==" instead of "=".
if (isbnTotal % 10 = 0) {
…should be:
if (isbnTotal % 10 == 0) {
Or better, reverse so compiler would have caught your typo.
if (0 == isbnTotal % 10) {
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;
}
So I'm practicing writing simple Java programs. I made one to change binary numbers to decimal. In last loop below all if(){}'s my program jumps to else without reason to do so. I've changed this last else to another if statement and program is running properly. But I wonder HOW it is possible that the first program is jumping to else. What property of if-else statements is making that?
Here is the code and outputs of both programs:
import java.util.Scanner;
public class NumberToBinary1 {
public static void main(String[] args) {
System.out.println("Put binary number: ");
Scanner sn = new Scanner(System.in);
String container = sn.nextLine();
System.out.println(binaryToNumber(container));
}
private static double binaryToNumber(String container) {
int numberLength = container.length();
double result = 0;
double power = 0;
for (int i = numberLength-1; i >= 0; i--) {
char a = container.charAt(i);
int x =a;
if (x == 49) { //if digit from binary number is 1 add 2^(number of power) to result
result += java.lang.Math.pow(2d, power);
power++;
}
if (x==48) { //if digit from binary number is 0, just skip to next power of 2
power++;
}
else {
System.out.println("issue with "+(i+1)+ " number"); //else give error with i+1th digit
}
}
return result;
}
}
Output:
Put binary number:
10110105
issue with 8 digit
issue with 6 digit
issue with 4 digit
issue with 3 digit
issue with 1 digit
90.0
#### AND SECOND:
import java.util.Scanner;
public class NumberToBinary1 {
public static void main(String[] args) {
System.out.println("Put binary number: ");
Scanner sn = new Scanner(System.in);
String container = sn.nextLine();
System.out.println(binaryToNumber(container));
}
private static double binaryToNumber(String container) {
int numberLength = container.length();
double result = 0;
double power = 0;
for (int i = numberLength-1; i >= 0; i--) {
char a = container.charAt(i);
int x =a;
if (x == 49) { //if digit from binary number is 1 add 2^(number of power) to result
result += java.lang.Math.pow(2d, power);
power++;
}
if (x==48){ //if digit from binary number is 0, just skip to next power of 2
power++;
}
if(x!=49 && x!=48) {System.out.println("issue with "+(i+1)+" digit"); //if digit from binary number is not 1 or 0 -> give error
}
}
return result;
}
}
Output:
Put binary number:
10110105
issue with 8 digit
90.0
Because in your first program else belongs only to second if statement, that's mean all values that not pass this if will go to else. In your second program you modified your statement. You can also try to modify your first program to this, it should give you the same result:
private static double binaryToNumber(String container) {
int numberLength = container.length();
double result = 0;
double power = 0;
for (int i = numberLength-1; i >= 0; i--) {
char a = container.charAt(i);
int x =a;
if (x == 49) { //if digit from binary number is 1 add 2^(number of power) to result
result += java.lang.Math.pow(2d, power);
power++;
} else if (x==48) { //if digit from binary number is 0, just skip to next power of 2
power++;
} else {
System.out.println("issue with "+(i+1)+ " number"); //else give error with i+1th digit
}
} return result;
}
I'm trying to write a programme to prompt the user to input an int which is above or equal 2. From this input the programme must then calculate and print the sum of all the even integers between 2 and the entered int. It must also produce an error message if the inputted int is below 2. I've made a programme for it that works but am just wondering if you guys could find a better way of doing it? I'm sure there is but I can't quite seem to find a way that works!
Here's what I did:
import java.util.Scanner;
public class EvenSum {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Enter an integer which is above 2.");
int number = scan.nextInt();
int divnum = number / 2;
int divnum2 = divnum + 1;
int sumofeven = divnum * divnum2;
if(number >= 2)
System.out.println("The sum of the even integers between the number is "+
sumofeven);
else
System.out.println("Invalid number entered.");
}
}
Note: do not use this example in a real context, it's not effective. It just shows a more clean way of doing it.
// Check the input.
if (number >= 2)
System.out.println(sum(number));
}
// Will find the sum if the number is greater than 2.
int sum(int n) {
return n == 2 ? n - 2 : n % 2 == 0 ? n + sum(n - 2) : sum(n - 1);
}
Hope this helps. Oh, by the way, the method sum adds the numbers recursively.
Sorry, but I had to edit the answer a bit. There might still be room for improvement.
Why do it with a loop? You can actually calculate it out. Let X be the number they choose. Let N be the largest even number <= X. (N^2+2*N)/4 will be your answer.
Edit: just saw the answer above me. He is right. I gave the function I suppose.
Why use a loop at all? You are computing the sum of:
2 + 4 + ... n, where n is a positive even number.
This is a very simple arithmetic progression.
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Enter an integer which is above 2.");
int number = scan.nextInt();
if (number >= 2) {
int sumofeven = 0;
for (int i = 2; i <= number; i += 2) {
sumofeven += i;
}
System.out.println("The sum of the even integers between the number is " + sumofeven);
} else {
System.out.println("Invalid number entered.");
}
}