Position of first significant digit after the decimal point - java

How can I calculate the position of the first significant digit in a fraction?
Here are a few example inputs with desired output
0.123456 // 1st sign. number position = 1
0.0012345 // ... = 3
0.000012345 // ... = 5

No need for looping. You can simply use the following formula:
Math.ceil(-Math.log10(d))
Example:
public static int firstSignificant(double d) {
return (int) Math.ceil(-Math.log10(d));
}
// Usage
System.out.println(firstSignificant(0.123456)); // 1
System.out.println(firstSignificant(0.0012345)); // 3
System.out.println(firstSignificant(0.000012345)); // 5
A note on some corner cases:
0 has no first significant digit. For this case the formula evaluates to Integer.MAX_VALUE.
You haven't specified what should happen with negative values, but if you want them to behave like positive values you can use Math.abs(d) instead of d in the formula.

You could loop over it count the number of times you need to multiply by ten before it becomes greater or equal to one:
public static int significantDigitNum (double d) {
int cnt = 0;
while (d < 1) {
d *= 10;
++cnt;
}
return cnt;
}
EDIT:
As David Conrad commented, this function will only work for positive numbers. To also support negatives:
public static int significantDigitNum (double d) {
int cnt = 0;
d = Math.abs(d);
while (d < 1) {
d *= 10;
++cnt;
}
return cnt;
}

You can check each character if it is a number between 1-9.
String numberString = "0.000012345";
int position = 1;
for(int i=0;i<numberString.length();i++){
if(String.valueOf(numberString.charAt(i)).matches("[1-9]")){
position=i-1;
break;
}
}

Related

I'm trying to convert a binary number to a decimal number but my Output is always 0

Here is my code. I tried to Convert the binary to a Char array, then multiply each char in the array by 2 to the power of its corresponding number in the array, then sum up all the values of the char array into a double. New to programming so a bit confused. My input Binary is txfBinaryInput, and my output label is lblDisplay.
private void btnProcessActionPerformed(java.awt.event.ActionEvent evt)
{
if (txfBinaryInput.getText().equals(""))
{
lblDisplay.setText("ERROR: NO INPUT");
} else
{
int n = 0;
int[] binaryValueStorage = new int[100];
double[] decimalValueStorage = new double[100];
String binaryInput = txfBinaryInput.getText();
int binaryNumber = binaryInput.length();
char[] binaryDigits = binaryInput.toCharArray();
for (int i = 0; i >= binaryNumber; i++)
{
binaryValueStorage[n] = binaryDigits[n];
decimalValueStorage[n] = binaryValueStorage[n] * (Math.pow(2, n));
n++;
}
double sum = 0;
for (double a : decimalValueStorage)
{
sum += a;
}
lblDisplay.setText("The Deciaml Value Is " + sum);
}
}
Beware: in your for loop condition, you have i >= binaryNumber instead of i < binaryNumber, therefore your program will never enter the loop!
And on a side note, why are you using two variables, i and n, for the same purpose (incrementing and accessing the array)?
Edit: another issue:
In binary numbers, lower order bits are to the right, but in arrays, indices are from left to right!!
So you want your rightmost digit to be multiplied by 2^0, the next one right to its left by 2^1, and so on.
But in your code, what is happening is the opposite: it is the leftmost digit (your digit at index 0) that is being multiplied by 2^0!
To fix, you can either:
1) reverse your binaryDigits array before starting to convert, and keep the rest of your code untouched
2) replace decimalValueStorage[n] = binaryValueStorage[n] * (Math.pow(2, n)); by decimalValueStorage[n] = binaryValueStorage[n] * (Math.pow(2, binaryNumber - n));
Hope this helps!
Well, this is a lot to throw at you, but this is how I'd attack this problem:
public class BinaryToDecimalTest {
private static long binaryToDecimal(String binaryInput)
{
long sum = 0;
for (int i = 0 ; i < binaryInput.length() ; i++) {
sum *= 2;
if (binaryInput.charAt(i) == '1')
sum += 1;
}
return sum;
}
private static void test(String binaryInput) {
long n = binaryToDecimal(binaryInput);
System.out.println(String.format("The Deciaml Value of %s Is %d", binaryInput, n));
}
public static void main(String...args) {
test("0100");
test("1011");
test("1011");
test("10000000");
test("10000000000000000");
}
}
Result:
The Deciaml Value of 0100 Is 4
The Deciaml Value of 1011 Is 11
The Deciaml Value of 1010 Is 10
The Deciaml Value of 10000000 Is 128
The Deciaml Value of 10000000000000000 Is 65536
I don't want to just hit you with code, but I didn't know where to start given all of the issues with your code. I wanted you to see how directly you can often attack a problem. I'd be happy to keep working with you, and explain what's going on here.
The one dirty trick I'm using is multiplying the entire accumulated sum by two each time around. This lets you work naturally from the front of the array, rather than having to work your way backwards. The first digit gets multiplied by 2 (length - 1) times, the second (length - 2) times, etc., down to the last number, which doesn't get multiplied at all.

Find the biggest palindrome in multiple integers

I have a problem with some algorithm. I must write a java app,
which find the biggest palindrome for the product of a predetermined amount of numbers (l) of a predetermined number of digits (n). For example for l=2 and n=2 the biggest palindrome is 9009 (91 * 99).
A palindrome checker I was writed, but I have no idea how to multiply the appropriate amount of numbers with a given number of digits.
Can anybody help me?
Sorry for my English.
Here is possible implementation of iteration through all combinations of l numbers with n digits:
public static int[] iterate(int l, int n) {
int minNum = (int) Math.pow(10, n - 1);
int maxNum = (int) Math.pow(10, n) - 1;
// init array with `l` numbers with `maxNum` value
int[] numbers = new int[l];
Arrays.fill(numbers, maxNum);
// iterate through all combinations of numbers
while (true) {
System.out.println(Arrays.toString(numbers)); // for debug only
// calc multiplication of current combination of numbers
long mul = 1;
for (int num : numbers) {
mul *= num;
}
if (isPalindrome(mul)) {
return numbers; // biggest palindrome found
}
// calc next combination of numbers
boolean allMaxNums = true;
for (int j = l - 1; j >= 0; --j) {
--numbers[j];
if (numbers[j] < minNum) {
numbers[j] = maxNum; // need to reduce next number, go to the next j
} else {
// now all numbers in [minNum, maxNum] bounds
allMaxNums = false;
break;
}
}
if (allMaxNums) {
break; // returned to the initial combination
}
}
return null; // palindrome not found
}
private static boolean isPalindrome(long mul) {
// your check here
return false;
}
EDIT
Unfortunately my previous solution is not right, we must iterate over combinations of numbers in descending order of its' products (not in some other order as i have done). I think that working code is better then my сhaotic explanations, so you can see my new solution here: https://ideone.com/ZSQC5d.

i want to print all armstrong number between 1 to 1000 in a textbox using awt or swing but i only get last value by my code .So plc help me

i want to print all armstrong number between 1 to 1000 in a textfield using awt or swing but i only get last value by my code .So pls help me
public void actionPerformed(ActionEvent e)
{
String s1=tf.getText();
int n1=Integer.parseInt(s1);
for(int n=0;n<10000;n++)
{
int sum=0;
int number=n;
int original=number;
while(number>0)
{
int r=number%10;
sum+=r*r*r;
number=number/10;
}
if(sum==original)
{
tf1.setText(String.valueOf(original[i]));
}
}
}
For those who don't know, an Armstrong number (or narcissistic number) is a number with n digits that is equal to the sum of each of its digits to the nth power.
(x1*10(n-1))+(x1*10(n-2))...+(x1*10(n-n)) = (x1)n+(x2)n...+(xn)n
This means that if the number is 1 digit, the power will be 1.
Therefore there are 10 1 digit numbers that are Armstrong numbers:
0 = 01
1 = 11
2 = 21
3 = 31
4 = 41
5 = 51
6 = 61
7 = 71
8 = 81
9 = 91
Your code, as written, will not identify any of those numbers as Armstrong numbers.
Your code will also incorrectly identify some numbers as 4 digit Armstrong numbers because you only look for the the cubes (3rd power) of your numbers not the 4th power.
(You don't have to worry about twos because there are no two digit Armstrong numbers)
In order to correctly determine all the possible Armstrong numbers between 1 and 10000, you need to write a "power" loop that finds the nth power of a number by multiplying the number n times.
This would look something like:
//... beginning of your original function
//added a string to hold all the values before printing
string holder = "";
for(int n=0;n<10000;n++){
int sum=0;
//n=original you had duplicate variables (just use n as original)
int number = n;
//while there are still digits left
while(number>0){
//get the smallest digit
int r=number%10;
//----------"Power" loop-----------
int foo = n;
//once smaller than 10, it's only a power of 1 (which is itself)
while(foo>=10){
//this means foo = foo/10
foo /= 10;
//this means r = r*r
r*=r;
}
//this means sum = sum+r
sum += r;
//you should have the hang of it by now
number/=10;
}
//if the sum equals the original number
if(sum==n){
//put that number into the end of a string (separated by newlines `\n`)
holder+=n+"\n";
}
}
//All done, so set the text box value
tf1.setText(holder);
//... whatever code you want to finish up
This should also take care of your problem with the textBox getting overwritten each time. By saving the numbers into a string and then printing all of them at once, only once (no overwriting), you'll get better results.
You always set the current found value. But you should set the previous found values + current found value.
tf1.setText(String.valueOf(original));
But more performant would be to use a stringbuilder object and append the result each time and set this value to the textfield outside the loop.
public void actionPerformed(ActionEvent e)
{
StringBuilder s = new StringBuilder ();
for(int n=0;n<10000;n++)
{
int sum=0;
int number=n;
int original=number;
while(number>0)
{
int r=number%10;
sum+=r*r*r;
number=number/10;
}
if(sum==original)
{
s.append(original + " ");
}
}
tf1.setText (stringBuilder.toString ());
}
Easy, all you do is change the setText() method of the TextField1 component with append().
It works! The remaining will do! Try it once.
public void actionPerformed(ActionEvent e)
{
String s1=tf.getText();
int n1=Integer.parseInt(s1);
for(int n=0;n<10000;n++)
{
int sum=0;
int number=n;
int original=number;
while(number>0)
{
int r=number%10;
sum+=r*r*r;
number=number/10;
}
if(sum==original)
{
tf1.append(String.valueOf(original[i] + " "));
}
}
}
Very simple program in C to list all armstrong number between 1 to 1000000.
#include<stdio.h>
#include<conio.h>
#include<math.h>
main()
{
long a = 1, c=0, b, e, f, d = 0,g=0,p,j,count=0;
printf("All armstron number between 1 and 1000000 is listed below!\n");
while (c <= 1000000)
{
j = c;
if (j >= 10)
{
while (j >= 10)
{
j = j / 10;
g++;
}
}
p = g + 1;
g = 0;
a = c;
f = a;
while (a >= 10)
{
b = a % 10;
d = d + pow(b,p);
a = a / 10;
}
e = pow(a,p) + d;
d = 0;
if (e == f)
{
count++;
printf("%ld\t",count );
printf("%ld\n", f);
}
c++;
}
getch();
}

Interview: Find the whole cubes between range of two Integers

I just gave a coding interview on codility
I was asked the to implement the following, but i was not able to finish it in 20 minutes, now I am here to get ideas form this community
Write a function public int whole_cubes_count ( int A,int B ) where it should return whole cubes within the range
For example if A=8 and B=65, all the possible cubes in the range are 2^3 =8 , 3^3 =27 and 4^3=64, so the function should return count 3
I was not able to figure out how to identify a number as whole cube. How do I solve this problem?
A and B can have range from [-20000 to 20000]
This is what I tried
import java.util.Scanner;
class Solution1 {
public int whole_cubes_count ( int A,int B ) {
int count =0;
while(A<=B)
{
double v = Math.pow(A, 1 / 3); // << What goes here?
System.out.println(v);
if (v<=B)
{
count=count+1;
}
A =A +1;
}
return count ;
}
public static void main(String[] args)
{
System.out.println("Enter 1st Number");
Scanner scan = new Scanner(System.in);
int s1 = scan.nextInt();
System.out.println("Enter 2nd Number");
//Scanner scan = new Scanner(System.in);
int s2 = scan.nextInt();
Solution1 n = new Solution1();
System.out.println(n.whole_cubes_count (s1,s2));
}
}
Down and dirty, that's what I say.
If you only have 20 minutes, then they shouldn't expect super-optimized code. So don't even try. Play to the constraints of the system which say only +20,000 to -20,000 as the range. You know the cube values have to be within 27, since 27 * 27 * 27 = 19683.
public int whole_cubes_count(int a, int b) {
int count = 0;
int cube;
for (int x = -27; x <= 27; x++) {
cube = x * x * x;
if ((cube >= a) && (cube <= b))
count++;
}
return count;
}
For the positive cubes:
i = 1
while i^3 < max
++i
Similarly for the negative cubes but with an absolute value in the comparison.
To make this more general, you need to find the value of i where i^3 >= min, in the case that both min and max are positive. A similar solution works if both min and max are negative.
Well, it can be computed with O(1) complexity, we will need to find the largest cube that fits into the range, and the smallest one. All those that are between will obviously also be inside.
def n_cubes(A, B):
a_cr = int(math.ceil(cube_root(A)))
b_cr = int(math.floor(cube_root(B)))
if b_cr >= a_cr:
return b_cr - a_cr + 1
return 0
just make sure your cube_root returns integers for actual cubes. Complete solution as gist https://gist.github.com/tymofij/9035744
int countNoOfCubes(int a, int b) {
int count = 0;
for (int startsCube = (int) Math.ceil(Math.cbrt(a)); Math.pow(
startsCube, 3.0) <= b; startsCube++) {
count++;
}
return count;
}
The solution suggested by #Tim is faster than the one provided by #Erick, especially when A...B range increased.
Let me quote the ground from github here:
"one can notice that x³ > y³ for any x > y. (that is called monotonic function)
therefore for any x that lies in ∛A ≤ x ≤ ∛B, cube would fit: A ≤ x³ ≤ B
So to get number of cubes which lie within A..B, you can simply count number of integers between ∛A and ∛B. And number of integers between two numbers is their difference."
It seems perfectly correct, isn't it? It works for any power, not only for cube.
Here is my port of cube_root method for java:
/*
* make sure your cube_root returns integers for actual cubes
*/
static double cubeRoot(int x) {
//negative number cannot be raised to a fractional power
double res = Math.copySign(Math.pow(Math.abs(x), (1.0d/3)) , x);
long rounded_res = symmetricRound(res);
if (rounded_res * rounded_res * rounded_res == x)
return rounded_res;
else
return res;
}
private static long symmetricRound( double d ) {
return d < 0 ? - Math.round( -d ) : Math.round( d );
}
I am aware of Math.cbrt in java but with Math.pow approach it is easy to generalize the solution for other exponents.

Iterate through each digit in a number

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++;
}
}

Categories