Sum Of Digits BigInteger - java

I was trying to find the sum of digits of a BigInteger and found this code.
BigInteger big = BigInteger.valueOf(2).pow(1000);
String digits = big.toString();
int sum = 0;
for(int i = 0; i < digits.length(); i++) {
int digit = (int) (digits.charAt(i) - '0');
sum = sum + digit;
}
System.out.println(sum);
I don't understand why - '0' is added in 6th line of the code.
int digit = (int) (digits.charAt(i) - '0');
If I remove that part it gives me a wrong answer.
For example sum of digits of 16 without - '0' gives 103 as the answer instead of 7.
So, can anyone explain the importance of that part in the code?
Any help is appreciated.

The code digits.charAt(i) gives you the ASCII code for the digit. So if you look at an ASCII table, you'll see the value of the character 7 is 55 and the value of character 0 is 48. If you subtract 0 from 7, you'll get 7, which is the digit you're looking for.

For example if you take a '5' from digits.getCharAt(i):
'5' - '0' = ?
According to the ASCII table Can be translated to:
53 - 48
Which is 5 and it's the result you're looking for

Related

Char variable minus char variable parse to Int in java

I know this is trivial, but I can't find the proper explication. I have the following code
str="1230"
int rez=str.charAt(3) - '0';
rez=3;
How does this parsing work?
As long as the character is a digit, you can get the equivalent int value by subtracting '0'. The ASCII coding for '0' is decimal 48, '1' is decimal 49, etc.
So '8' - '0' = 56 - 48 = 8;
For your number, you can parse the entire string like this (assuming all the characters are digits, otherwise the result wouldn't make sense).
String v = "1230";
int result = 0; // starting point
for (int i = 0; i < v.length(); i++) {
result = result* 10 + v.charAt(i) -'0';
}
System.out.println(result);
Prints
1230
Explanation
In the above loop, first time thru
result = 0 * 10 + '1'-'0 = 1
second time thru
result = 1 * 10 + '2'-'0' = 12
third time thru
result = 12 * 10 + '3'-'0' = 123
last time thru
result = 123 * 10 + '0'-'0' = 1230
"Behind the scene" a char is just an int with a specific range (very simplified explanation).
Try following code to convince yourself:
System.out.println((int) '0'); // this won't output 0
System.out.println((int) 'a'); // this work as well
This is why arithmetic operations are possible on chars.

calculate Check Number in Java

Not sure if anyone can explain this to me or help me.
I have a 15 Digit Number of which I want to multiply each even number by 2 unless the even number is greater than 9. If it is this needs to be subtracted by 9 to give me an integer that again I can multiply by 2. Once I have all the even numbers multiplied by 2 i need to add them all together with the odd numbers.
Does that make sense.
UPDATE ***
so i have a number say 49209999856459. for that number I am looking to get the even integer so for example the first even one would be 4 then the second would be 2 and so on.
If one of those even numbers are multiplied by 2 then it might be above 9 so I want to subtract 9 to then use the remainder as the even number in its place.
SO !!!
Multiply by 2 the value of each even digit starting from index 0 and then each even index. In each case, if the resulting value is greater than 9, subtract 9 from it (which reduces larger values to a single digit). Leave the values of the digits at the odd indexes unchanged.
public String calculateCheckNumber()
String firstFifteen = longNumber.substring(0,15) ;
int i, checkSum = 0, totalSum = 0;
for (i = 0; i<firstFifteen.length(); i += 2) {
while (i < 9)
i *= 2;
if (i > 9)
i -= 9 ;
}
Was one option I was trying but it honestly I cant seem to get my head around it.
Any Help would be greatly appreciated.
Well, here is one approach. This uses the ternary (?:) operator to condense the operations. Edited base on clarification from the OP. The example you gave is actually a 14 digit string. But the following will work with any number of digits if they start out in a string. If you have a long value, then you can create the character array using:
long v = 49209999856459L;
char[] d = Long.toString(v).toCharArray();
Here is the main algorithm.
String s = "49209999856459";
int sum = 0;
char[] d = s.toCharArray();
for (int i = 0; i < d.length; i++) {
int v = d[i] - '0';
// The even digit will only be greater than 9 after
// doubling if it is >= 5 before.
sum += ((i % 2) == 1) ? v : (v >= 5) ? v+v-9 : v+v;
}
System.out.println(sum);
Prints
86

Negative string index

I am doing some kind of cipher in Java for schools homework. The task is to change the value of a certian char to a new one with a specific offset which is given by the user and has a range from negative numbers to positive numbers (alphabet).
Now I have a problem with negative offsets. I have created a String with the Alphabet which helps to find the new char. For example: With the offset of 7 I got this: encrypt(“TEST”) = “ALZA”. So my code grabs the index of the string value and searches with this index in the alphabet string for the new char. Anyway when I now have the char 'E' and a negative index i.e '-7' it will return the value of -3 for the new index of the new char (I hope that makes sense). Since there is no char on index '-3' I get an error.
So how can I access to the end of the string instead of going more and more into negative index numbers ?
Add 26 then mod 26:
i = (i + 26) % 26;
This always works for indexes down to -26. If that's not enough, just add some zeroes:
i = (i + 26000000) % 26;
Your general problem appears to be that letters are represented by only 26 indices, but the actual index variable you use might be greater than 26, or even less than zero (negative). One way to handle this problem is to use the mod operator to safely wrap your index around to always point to a range containing a valid letter.
Here is logic which can do that:
if (index < 0) {
index = (index % 26) + 26;
}
else {
index = index % 26;
}
Assuming the letter E is position 5 and you have a reassignment of -7, this would mean that the new index would be -2. This new position can be mapped using the above logic as follows, where index = -2 in this case:
5 - 7 = -2
(-2 % 26) + 26
-2 + 26
24
And character in position 24 is the letter X.
If you can constrain shift values to be positive, you can use remainder operator:
int newIndex = (index + shift) % 26
If there are negatives to be expected:
int newIndex = Math.floorMod(inndex + shift, 26) would do the trick
Actually you need mathematical modulo, but % operator is not quite that

Only 7 bits for Java char?

I'm trying to make a UUencode algorithm and part of my code contains this:
for(int x = 0; x < my_chars.length; x++)
{
if((x+1) % 3 == 0)
{
char first = my_chars[x-2];
char second = my_chars[x-1];
char third = my_chars[x];
int first_binary = Integer.parseInt(Integer.toBinaryString(first));
int second_binary = Integer.parseInt(Integer.toBinaryString(second));
int third_binary = Integer.parseInt(Integer.toBinaryString(third));
int n = (((first << 8) | second) << 8) | third;
System.out.print(my_chars[x-2] + "" + my_chars[x-1] + my_chars[x] + Integer.toBinaryString(n));
}
}
System.out.println();
System.out.println(Integer.toBinaryString('s'));
What I'm trying to achieve is to combine those 8 bits from the chars that I get into a big 24 bits int. The problem I'm facing is that the result is a 23 bit int. Say my first 3 chars were:
'T' with a binary representation of 01010100
'u' with a binary representation of 01110101
'r' with a binary representation of 01110010
The result that I get from my program is a int formed from these bits:
10101000111010101110010
Which is missing the 0 at the beginning from the representation of 'T'.
Also I have included the last 2 lines of code because the binary string that I get from 's' is: 1110011 which is missing the 0 at the beginning.
I have checked if I scrolled by mistake to the right but it does not seem that I have done so.
The method Integer.toBinaryString() does not zero-pad the results on the left; you'll have to zero-pad it yourself.
This value is converted to a string of ASCII digits in binary (base 2)
with no extra leading 0s.

Want to Convert decimal value in 2 raised to format and want to know its power of 2 in java

I have one decimal value like 65 and I want to divide this value in 2 raised to format.
For example, I have this type rule:
If I get 42 as a decimal number, I want to divide first 42 number in format of 2 raised to. Then, I want to output its power only, like:
OutPut : 1,3,5
For example, if I have 65 as a decimal number, then I want 6,0 as its output, because (2 raised to 6) + (2 raised to 0) = 65.
Thanks
Anybody can help me how I can achieve this thing in Java.
You can repeatedly compare the least significant bit, counting as you go, and right-shifting the number to look at each bit in turn:
int n = 65
int d = 0;
while (n > 0) {
if ((n & 1) == 1) { // check LSB
System.out.println(d);
}
n >>>= 1; // shift right
++d; // inc digit count
}
Integer.toString(65, 2);
Does the following output:
1000001
Then you work on the String.
This can be improved, but I think it'll do the job.
int n = 42;
String binary = Integer.toBinaryString(n);
for(int i = binary.length() - 1; i >= 0; i--){
if(binary.charAt(i) == '1')
System.out.print(i+1);
}
Here is the algorithm:
Find a log base 2 of given number x=log(2, input)
Find the floor and the ceiling of the result y = floor(x), z=ceiling(x)
Find 2^y, 2^z and choose the one closer to the input.
calculate the diff = (input - 2^(x or y)) and do the same for the diff recursively until dif=0.

Categories

Resources