How to use the equivalent of indexof() with biginteger in VB.Net? - java

I am trying to sum up the digits in a very large number. I have gotten the length of the number with
l = answer.bitLength() but I can't figure out how to increament through each digit using a For loop. Any ideas?
I'm using the java.math.biginteger.
Visual Studio 2005 Version 2.0
I should also add that I can't seem to use <> or any of the simple math options with the biginteger I'm using. If anyone could tell me how to use a different biginteger I would be more than willing to swap.
Dim answer As java.math.BigInteger
Dim sum As Integer = 0
Dim x As Integer
Dim i As Integer
'Sets value of answer equal to 1
answer = java.math.BigInteger.valueOf(1)
'gets 100!
For i = 1 To 100
answer = answer.multiply(java.math.BigInteger.valueOf(i))
Next
'gets length of answer
Dim l As Integer
l = answer.bitLength()
'Sums up digits in 100!
For x = 0 To l - 1
'Need to pull each character here to add them all up
Next
Final Solution for summing up the digits. Thanks to wageoghe.
Dim r As Integer
Dim s As Integer
s = 0
While (answer.compareTo(java.math.BigInteger.valueOf(0)) > 0)
r = answer.mod(java.math.BigInteger.valueOf(10)).ToString()
s = s + r
answer = answer.divide(java.math.BigInteger.valueOf(10))
End While

Something like this should work:
Dim bi As New System.Numerics.BigInteger(12345)
Dim c As Char
Dim s As Long
s = 0
For Each c In bi.ToString()
s = s + Integer.Parse(c.ToString())
Next
Or this more conventional way using Mod and / (integer division)
Dim bi As New System.Numerics.BigInteger(12345)
Dim s As Long
Dim r As Integer
s = 0
While bi <> 0
r = bi Mod 10
s = s + r
bi = bi / 10
End While

If you think of the number as a list of binary characters, then you could get the least significant hex digit by ANDing the number with 0xF. If you then shifted the number right by 4 bits (>> 4), then you could get the next hex digit.
After you get all of the hex digits, you could sum them up and then convert them to decimal.

Another approach, is to do the following (this assumes that answer is positive):
int sum = 0;
while(answer > 0){
sum += answer % 10;
answer /= 10;
}

Related

Adc Conversion quantization

double vDeltaRef, vPlusRef = 10, vMinusRef = 0, q, n, nExp = 3;
vDeltaRef = vPlusRef - vMinusRef;
n = Math.pow(2, nExp);
q = vDeltaRef / n;
System.out.println(q);
the result from the formula is 1.25v
this value:
How can I translate the obtained result
Since you know vPlusRef, vMinusRef and nExp, you can always calculate q (which is 1.25 in this case).
Then, to convert from digital to analog simply multiply the digital value with q. For example the 3-bit value 011, which is 3 in decimal, will be converted to 3.75 which is the lower bound of the required range 3.75 to 5.00.
Finally, to convert from analog to digital do:
int digitalValue = (int) Math.floor(analogValue / q);
For example an analog value of 8.19 would return 6, which is the 3-bit value 110.

Why is this solution to Reverse Integer (Leet Code) O((log10(n))?

The problem in question asks to reverse a 32-bit signed integer. Here's the given solution in Java:
public int reverse(int x) {
int rev = 0;
while (x != 0) {
int pop = x % 10;
x /= 10;
if (rev > Integer.MAX_VALUE/10 || (rev == Integer.MAX_VALUE / 10 && pop > 7)) return 0;
if (rev < Integer.MIN_VALUE/10 || (rev == Integer.MIN_VALUE / 10 && pop < -8)) return 0;
rev = rev * 10 + pop;
}
return rev;
}
}
​According to the solution's explanation, it's time complexity is O(log10(n)) because there are roughly log10(x) digits in x. Intuitively, there seems to be n-1 iterations of the while loop, where n is the number of digits. (I.E: a 7 digit number requires 6 iterations) However, the solution and given complexity implies that the n is the integer itself and not the number of digits. Can anyone help me gain an intuitive understanding of why the above solution is log10(n) ?
If x is an integer, then floor(log10(x)) + 1 is equal to the number of digits in x.
Let log(10)x = some number y. Then 10^y = x.
For example,
log(10) 10 = 1
log(10) 100 = 2
log(10) 1000 = 3
...
When x is not a perfect power of 10:
floor( log(213) ) = 2
Let me know if this doesn't answer your question.
Let's say the x = 123.
int rev = 0;
rev = rev * 10 + x % 10; // rev = 3, 1st iteration.
x = x/10; // x = 12
rev = rev * 10 + x % 10; // rev = 3 * 10 + 2 = 32, 2nd iteration
x = x/10; // x = 1
rev = rev * 10 + x % 10; // rev = 32 * 10 + 1 = 321, 3rd iteration.
x = 0 so the loop terminates after 3 iterations for 3 digits.
The conditionals within the loop check to see if the reversed values would exceed what a 32 bit number could hold.
So it is log10(n) exactly for the reason you stated in your question. The log of a number n to a given base is the exponent required to raise the base back to the number n. And the exponent is an approximation of the number of digits in the number.
Based on your comment, it could also have been stated that "For any number n, where m is the the number of digits in n, the time complexity is O(m)."
The given reverse algorithm requires in the worst case log_10(x) iterations. In other words, if the given input x consists of k decimal digits, it requires k iterations. But stating that this algorithm is O(log_10(x)) is misleading. This is not logarithmic algorithm. If the input size is not intuitive (for example, testing whether given integer is a prime), we need to rigorously apply the correct definition of input size. In Big O analysis, the input size is defined as the number of characters it takes to write the input. Since we normally encode integers in binary digits, the input size of this algorithm n is approximately log_2 x. Therefore, x is roughly 2^n. The worst case complexity W(x) = log_10 (x) = log_10(2^n) = n log_10(2). Therefore, the big O of reverse algorithm is O(n).

Converting int to string in java is giving the answer as 1

I converted a decimal integer to binary and that binary integer when I'm trying to convert to a string is giving me 1 as the answer always when it should give the value of the string.
while(a>0)
{
b = a%2;
n = b;
a = a/2;
System.out.print(n);
}
String m = Integer.toString(n);
System.out.print(m);
Any corrections and suggestions would be much appreciated.
Thanks!
On every loop step, you have these two statements:
b = a % 2;
n = b;
Think about why all the possible values of n are 0 and 1?
It's because n copies the value of b, which is the value of a modulo 2, which is always 0 or 1.
The last value of n will be the left-most bit of the binary representation of a, which will be always 1 (unless a is 0) and this is why you always get 1 when printing m.
When you use
n = b;
you are replacing the value of n each time. What you want it to accumulate the bits in n. The simplest way to do this is to use a StringBuilder.
StringBuilder sb = new StringBuilder();
while (a > 0) {
int lowest = a & 1;
sb.insert(0, lowest);
a = a >>> 1; // shift the bits down by 1.
}
String m = sb.toString();
System.out.print(m);
This will do the same thing as Integer.toString(a, 2)

Java Math convert to Integer

I am trying to convert my float value into Integer, but I cannot convert it. It says cannot find symbol. Are there any ways to do this.
This is my java code:
float upper = 999999;
float lower = 100000;
Integer ReceiptNo = 0;
Random rnd = new Random();
ReceiptNo = Math.round((Math.floor( (upper - lower + 1) * rnd() ) )) + lower;
This is my vb code:
Dim upper As Single = 999999 'Set the upper limit of random number.
Dim lower As Single = 100000
Dim ReceiptNo As Integer = 0
Randomize() 'Need to randomise the random number or else the number generated is always the same
ReceiptNo = CInt(Math.Floor((upper - lower + 1) * Rnd())) + lower
I am trying to reuse the vb code in java. Thank you.
rnd is an instance variable, not a method, so you can't write rnd().
You can write :
ReceiptNo = (int)(Math.round((Math.floor( (upper - lower + 1) * Math.random() ) )) + lower);
I'm not sure what Rnd() does in VB, but if it produces a random double between 0 and 1, that's what Math.random() does.
It seems that should be rnd.nextFloat() instead of rnd()
http://docs.oracle.com/javase/7/docs/api/java/util/Random.html
Dim prng As New Random 'do NOT put this in a method
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
Dim upper As Integer = 999999 + 1 'Set the upper limit of random number.
Dim lower As Integer = 100000
Dim ReceiptNo As Integer = prng.Next(lower, upper) 'the upper is exclusive
End Sub
rnd here is an object of the class Random. Objects can't be used as rnd().
The correct code should be ReceiptNo = Math.round((Math.floor( (upper - lower + 1) * Math.random() ) )) + lower;
For more learning on java classes and objects here is good http://www.tutorialspoint.com/java/java_object_classes.htm
Use Math.random() instead of rnd().
You need to cast the value from Math.round (it's returning float) to int
ReceiptNo = (int) (Math.round((Math.floor( (upper - lower + 1) * Math.random() ) )) + lower);

Why is myArrayList.size(); producing incorrect/gigantic numbers?

Basically, I'm trying to write a program that converts a number from base 2 to base 10. What I tried doing was translating the process listed on this website under the "Doubling method" into a for loop, but for some reason the numbers I'm getting are way to big.
The basic formula is (2 * previousTotal) + (currentDigit of the ArrayList that holds the user's inputted binary number) = previousTotal.
So for 1011001 in binary, the math would be:
(0 x 2) + 1 = 1
(1 x 2) + 0 = 2
(2 x 2) + 1 = 5
(5 x 2) + 1 = 11
(11x 2) + 0 = 22
(22 x 2) + 0 = 44
(44 x 2) + 1 = 89
The console however, prints out 6185 as the result. I'm thinking it might have something to do with me using an ArrayList of characters, but the charWhole.size() returns 7, which is how many digits are in the user's binary number. As soon as I do charsWhole.get(w); however, I start getting big numbers such as 49. I'd really appreciate some help!
I wrote out this loop, and according to some print statements that I placed throughout the code and my variable addThis seems to be where the problem is. The console prints out a final total of 6185, when 1011001 in base 10 is actually 89.
public static void backto2(){
System.out.println("What base are you coming from?");
Scanner backToB10 = new Scanner(System.in);
int bringMeBack = backToB10.nextInt();
//whole
System.out.println("Please enter the whole number part of your number.");
Scanner eachDigit = new Scanner(System.in);
String theirNumber = eachDigit.nextLine();
String str = theirNumber;
ArrayList<Character> charsWhole = new ArrayList<Character>();
for (char testt : str.toCharArray()) {
charsWhole.add(testt);
}
System.out.println(theirNumber); // User's number
System.out.println(charsWhole); // User's number separated into elements of an ArrayList
System.out.println(charsWhole.size()); // Gets size of arrayList, comes out as 7 which seems fine.
int previousTotal = 0, addThis = 0, q =0;
for( int w = 0; w < charsWhole.size(); w ++) {
addThis = charsWhole.get(w); //current digit of arraylist PROBLEM
q = previousTotal *2;
previousTotal = q + addThis; // previous total gets updated
System.out.println(q);
System.out.println(addThis);
System.out.println(q + " and " + addThis + "equals " + previousTotal);
}
System.out.println(previousTotal);
You are attempting to add a character to an integer. The implicit conversion uses the ASCII value of the character, so that '1' gets converted to 49, not 1, because 49 is the code for the character '1'. Subtract '0' to get the actual integer value.
addThis = charsWhole.get(w) - '0';
This works because the digits 0-9 are represented in ASCII as the codes 48-57, so in effect you will, for '1', subtract 49 - 48 to get 1.
You'll still have to handle cases when the character is outside the range of allowable characters.
EDIT
Java uses Unicode, but for the purposes of the codes for the digits 0-9, the codes are the same (48 thru 57, or 0x30 thru 0x39) in both ASCII and Unicode.
The problem is that you're using the chars rather than the number value they represent. In the line
addThis = charsWhole.get(w);
the value of addThis is the ascii value of the character. For '0', this is 48. Use this instead:
addThis = Integer.parseInt(charsWhole.get(w));
Another suggestion to solve the same problem:
addThis = charsWhole.getNumericValue(w);
See here for more information.

Categories

Resources