Multiply the number based on its length - java

I wanted to multiply the number based on its String length.
For example
String s = "153";
So, here the length of the above string is 3. So i wanted to multiply each number in the string 3 times (which is the actual length of the string)
Something like below
Here the length is 3
Something like this 1*1*1+5*5*5+3*3*3
Can anyone please help me in that?
This is what I have tried:
int number = 153;
String originalNumber = number+"";
char[] ch = originalNumber.toCharArray();
int length = originalNumber.length();
for (int i = 0; i < ch.length; i++) {
char c = ch[i];
for (int j = 0; j < ch.length; j++) {
// I'm stuck here
}
}

So you have to take each digit and take it to the power of the length of your string, then add all those results up.
You could do the following:
String s = "153";
int result = 0;
for (char n : s.toCharArray())
if (Character.isDigit(n))
result += Math.pow(Character.getNumericValue(n), s.length());
System.out.println(result);
It prints:
153
I added a safety check to see if the char is actually a digit (if (Character.isDigit(n))).

Classic solution : You need to turn each char, in an int then use use power to the length and sum all :
int res = 0;
for (int i = 0; i < ch.length; i++) {
int newNb = (int) Math.pow(Character.digit(ch[i], 10), ch.length);
res += newNb;
}
for-each loop solution
for (char c : ch) {
int newNb = (int) Math.pow(c - '0', ch.length);
res += newNb;
}
To turn a char c to its corresponding int value you can do :
int a = Character.getNumericValue(c);
int a = Character.digit(c, 10);
int a = c - '0';

You could simply iterate over each digit of the given string and calculate it's power. It is better to use str.charAt(i) instead of str.toCharArray() to not create additional char[].
public static int multiplyNumberLength(String str) {
int res = 0;
for (int i = 0; i < str.length(); i++)
if (Character.isDigit(str.charAt(i)))
res += Math.pow(str.charAt(i) - '0', str.length());
return res;
}

To turn a character back into a digit:
char c = ch[i];
int digit = c - '0';
int product = 1;
then for your inner loop multiply the digit into the product.

Related

(Java Code) Return maximum occurring character in an input string

Can anyone please explain the process of this for loop which comes first in the code. If you print these two lines in the console, you get output [0 0 0 1 2]. I don't know "how it works behind the scene to increment the character count every time".
for (int i=0; i<len; i++)
count[str.charAt(i)]++;
//Code
public class GFG
{
static final int ASCII_SIZE = 256;
static char getMaxOccuringChar(String str)
{
// Create array to keep the count of individual
// characters and initialize the array as 0
int count[] = new int[ASCII_SIZE];
// Construct character count array from the input
// string.
int len = str.length();
for (int i=0; i<len; i++) //bit confused lines
count[str.charAt(i)]++;
int max = -1; // Initialize max count
char result = ' '; // Initialize result
// Traversing through the string and maintaining
// the count of each character
for (int i = 0; i < len; i++) {
if (max < count[str.charAt(i)]) {
max = count[str.charAt(i)];
result = str.charAt(i);
}
}
return result;
}
// Driver Method
public static void main(String[] args)
{
String str = "abcaa";
System.out.println("Max occurring character is " +
getMaxOccuringChar(str));
}
}
The for loop iterates over the string, the value of str.charAt(i) is the character of str at the index i.
Since every char corresponds to an int value (see more about that here) count[str.charAt(i)]++; increases the value of the count array at the index of the given char's corresponding int (see the ascii table to see which one that is).
So after the for loop count contains the number of occurences of every ascii character in str.
str.charAt(i) return char from str at the i position. Char can be used as index in array for example myarray['c'] because 'c' can be represented as number (see ASCII table).
So basically
for(int i=0; i<len; i++)
count[str.charAt(i)]++;
is counting how many times the same letter appears in string.
so for input string "aabc"
count['a'] = 2
count['b'] = 1
count['c'] = 1
Maximum occurring character in a single input string
public static char getMaxOccuringChar(String str) {
char result = ' ';
int len = str.length();
HashMap<Character, Integer> StrArray = new HashMap<Character, Integer>();
int val = 1;
for(int i =0; i<len; i++) {
char temp = str.charAt(i);
if(!StrArray.containsKey(temp)) {
StrArray.put(temp, val);
}else {
StrArray.put(temp, StrArray.get(temp)+1);
}
}
int MaxVal = 0;
for(char i : StrArray.keySet()) {
if(StrArray.get(i) > MaxVal) {
result = i;
MaxVal = StrArray.get(i);
}
}
return result;
}

Putting all 8-bit binary sequences into a string array Java

what I am trying to put all possible 256 binary bit sequences into a string array. In order to do that, I have created 8 for loops to have all the possible cases. Here's what I've tried so far.
static String[] BitSequences() {
int[] result = new int[256];
for (int a = 0; a < 256; a++) {
for (int i = 0; i < 2; i++){
for (int j = 0; j < 2; j++){
for (int k = 0; k < 2; k++){
for (int l = 0; l < 2; l++){
for (int m = 0; m < 2; m++){
for (int n = 0; n < 2; n++){
for (int o = 0; o < 2; o++){
for (int p = 0; p < 2; p++){
result[a] = ; //this part is a problem
}
}
}
}
}
}
}
}
}
String str = Arrays.toString(result);
System.out.println(str);
return str;
}
This method is supposed to return a string array that contains all the possible cases. However, I don't know how to insert these value by making for-loops using int values. It is easy to print it out:
'
System.out.println(i+j+k+.....+p)
'
any help would be appreciated!
Consider using the built in conversion method for binary strings:
static String[] BitSequences() {
String[] result = new String[256];
for (int a = 0; a < 256; a++) {
result[a] = Integer.toBinaryString(a);
}
String str = Arrays.toString(result);
System.out.println(str);
return str;
}
An 8-bit, two's complement integer ranges from -128 to 127. To represent that range, we can use IntStream#rangeClosed.
From this answer, we can utilize BigInteger to left-pad the binary String (generated by Integer#toBinaryString) with 0s if its length is less than 8 (denoting that the value is positive).
Otherwise, the value represents a negative number, and its respective binary string will have a length greater than 8, which must be truncated to 8 characters using String#substring.
Finally, the Stream<String> can be collected to a String[] using Stream#toArray.
public static String[] generateBitSequences() {
return IntStream.rangeClosed(-128, 127)
.mapToObj(Integer::toBinaryString)
.map(BigInteger::new)
.map(b -> String.format("%08d", b)) // Left pad positive values with 0s.
.map(s -> s.substring(s.length() - 8)) // Remove leading 1s from negative values.
.toArray(String[]::new);
}
Output:
[10000000, 10000001, ..., 01111110, 01111111]

Java get each digit from 2 strings and calculate it

The task is asking me to insert 2 strings of a very huge number and sum them from right to left like the way we studied in primary school like:
23 + 28 =
(2 + 2 + <1> (this is the left 1 >>> keep reading ))(3 + 8 (give the left <1> from 11 sum with the two front numbers)) =
51.
The algorithm is ok but when I try to do like (just default that the 2 number has the same length so I get lenA and not greater than 10 to make easier):
int len = a.length();
String result="";
for(int i = len; i>0 ; i--) { //<- We only need it to loop how many times
result = Integer.valueOf( a.charAt(len-1) ) + Integer.valueOf( b.charAt(len-1) ) + "" + result;//<<<because we sum them from right to left
lenA--; lenB--;
}
and that (<<<) line always give me the error.
This is just one of a many ways I tried if it's wrong and you have a solution, please just guide me, sometimes i think too much and forgot a lot of small details :))
So the question here is how can i change it from a digit of String to Integer, calculate it and print out String again. But after I read the .charAt() info it said: "Returns the char value at the specified index." so the question maybe confuse between the first question and Convert from a digit from String use charAt -> become Char then convert Char to Integer to calculate and finally convert back to String so that I can + with String result.
I tried a lot of way but still can't solve it.
int lena = a.length();
int lenb = b.length();
int inta[] = new int[lena];
int intb[] = new int[lenb];
int result[];
int carry = 0, maxLen = 0, tempResult;
if(lena >lenb)
maxLen = lena + 1;
else
maxLen = lenb + 1;
result = new int[maxLen];
for(int i = lena - 1; i>=0 ; i--) {
inta[i] = Integer.valueOf( a.charAt(i) );
}
for(int i = lenb - 1; i>0 ; i--) {
intb[i] = Integer.valueOf( b.charAt(i) );
}
for(int i = maxLen - 1; i >= 0; i--) {
result[i] = 0;
}
for(int i = 1; i < maxLen - 1; i++) {
tempResult = 0;
if(lena > i)
tempResult += inta[lena - i];
if(lenb > i)
tempResult += intb[lenb - i];
result[maxSize - i] += tempResult % 10;
result[maxSize - i - 1] = tempResult / 10;
}
String res = "";
for(int i = 0; i < maxLen; i++) {
res += result[i];
}
System.out.println(res);
I think that would do what you want and will avoid most simple mistakes (couldn't try it, no acces to an IDE).
I actually separate the two string into their inside number and then add them into the result tab.
Then I put the result tab into a string that I print.

Trie Data Structure in Finding an Optimal Solution

This Question is part of ongoing Competition , I have solved the 75% of this Question Data Set but the 25% is giving me TLE. I am asking why it's is giving TLE an i am sure my complexity is O(n*n)Question:
String S consisting of N lowercase English alphabets. We has prepared a list L consisting of all non empty substrings of the string S.
Now he asks you Q questions. To ith question, you need to count the number of ways to choose exactly Ki equal strings from the list L
For Example:
String = ababa
L = {"a", "b", "a", "b", "a", "ab", "ba", "ab", "ba", "aba", "bab", "aba", "abab", "baba", "ababa"}.
k1 = 2: There are seven ways to choose two equal strings ("a", "a"), ("a", "a"), ("a", "a"), ("b", "b"), ("ab", "ab"), ("ba", "ba"), ("aba", "aba").
k2 = 1: We can choose any string from L (15 ways).
k3 = 3: There is one way to choose three equal strings - ("a", "a", "a").
k4 = 4: There are no four equal strings in L .
Question LINK
My approach
I am making a TRIE of IT and Calculating The and Array F[i] where F[i] represent the number of times i equal String Occur.
My TRIE:
static class Batman{
int value;
Batman[] next = new Batman[26];
public Batman(int value){
this.value = value;
}
}
MY Insert Function
public static void Insert(String S,int[] F , int start){
Batman temp = Root;
for(int i=start;i<S.length();i++){
int index = S.charAt(i)-'a';
if(temp.next[index]==null){
temp.next[index] = new Batman(1);
F[1]+=1;
}else{
temp.next[index].value+=1;
int xx = temp.next[index].value;
F[xx-1]-=1;
F[xx]+=1;
// Calculating The Frequency of I equal Strings
}
temp = temp.next[index];
}
}
MY MAIN FUNCTION
public static void main(String args[] ) throws java.lang.Exception {
Root = new Batman(0);
int n = in.nextInt();
int Q = in.nextInt();
String S = in.next();
int[] F = new int[n+1];
for(int i=0;i<n;i++)
Insert(S,F,i);
long[] ans = new long[n+1];
for(int i=1;i<=n;i++){
for(int j=i;j<=n;j++){
ans[i]+= F[j]*C[j][i]; // C[n][k] is the Binomial Coffecient
ans[i]%=mod;
}
}
while(Q>0){
Q--;
int cc = in.nextInt();
long o =0;
if(cc<=n) o=ans[cc];
System.out.println(o+" "+S.length());
}
}
Why My appraoch is giving TLE as time Complexity is O(N*N) ans the length of String is N<=5000. Please Help me Working CODE
One reason this program get TLE (keep in mind that time constraint is 1 sec):
Each time you create a Batman object, it will create an array with length [26], and it is equivalence to adding a loop with n = 26.
So, you time complexity is 26*5000*5000 = 650000000 = 6.5*10^8 operations, theoretically, it can still fit into time limit if CPU speed is 10^9 operations per sec, but also keep in mind that there are some heavy calculation stuffs after this, so, this should be the reason.
To solve this problem, I used Z-algorithm and get accepted: Link
The actual code is quite complex, so the idea is, you have a table count[i][j], which is the number of substring that matched substring (i, j). Using Z-algorithm, you can have a time complexity of O(n^2).
For each string s:
int n = in.nextInt();
int q = in.nextInt();
String s = in.next();
int[][] cur = new int[n][];
int[][] count = new int[n][n];
int[] length = new int[n];
for (int i = 0; i < n; i++) {
cur[i] = Z(s.substring(i).toCharArray());//Applying Z algorithm
for (int j = 1; j < cur[i].length; j++) {
if (cur[i][j] > length[j + i]) {
for (int k = i + length[j + i]; k < i + cur[i][j]; k++) {
count[i][k]++;
}
length[j + i] = cur[i][j];
}
}
}
int[] F = new int[n + 1];
for(int i = 0; i < n; i++){
for(int j = i; j < n; j++){
int v = count[i][j] + (length[i] < (j - i + 1) ? 1 : 0);
F[v]++;
}
}
Z-algorithm method:
public static int[] Z(char[] s) {
int[] z = new int[s.length];
int n = s.length;
int L = 0, R = 0;
for (int i = 1; i < n; i++) {
if (i > R) {
L = R = i;
while (R < n && s[R - L] == s[R])
R++;
z[i] = R - L;
R--;
} else {
int k = i - L;
if (z[k] < R - i + 1) {
z[i] = z[k];
} else {
L = i;
while (R < n && s[R - L] == s[R])
R++;
z[i] = R - L;
R--;
}
}
}
return z;
}
Actual code: http://ideone.com/5GYWeS
Explanation:
First, we have an array length, with length[i] is the longest substring that matched with the string start from index i
For each index i, after calculate the Z function, we see that, if cur[i][j] > length[j + i], which means, there exists one substring longer than previous substring matched at index j + i, and we havent counted them in our result, so we need to count them.
So, even there are 3 nested for loop, but each substring is only counted once, which make this whole time complexity is O(n ^2)
for (int j = 1; j < cur[i].length; j++) {
if (cur[i][j] > length[j + i]) {
for (int k = i + length[j + i]; k < i + cur[i][j]; k++) {
count[i][k]++;
}
length[j + i] = cur[i][j];
}
}
For below loop, we notice that, if there is a matched for substring (i,j), length[i] >= length of substring (i,j), but if there is no matched, we need to add 1 to count substring (i,j), as this substring is unique.
for(int j = i; j < n; j++){
int v = count[i][j] + (length[i] < (j - i + 1) ? 1 : 0);
F[v]++;
}

Convert char A-Z to corresponding int.

i am trying to convert A char from an array (2nd and 3rd) slot to int value that correspond to eg. A = 1 , B= 2, etc. For A-Z.
I am thinking that the long way will be doing if(x.charAt(i) == 'a'){ int z = 1; } for the whole A - Z which i think it is a very practical method. Is there any method that can do the same thing with a shorter code?
public static void computeCheckDigit(String x){
char [] arr = new char[x.length()];
for(int i=0; i<x.length();i++){
arr[i] = x.charAt(i);
}
}
Try this:
arr[i] = Character.toLowerCase(x.charAt(i)) - 'a' + 1;
You have to use int Array instead char Array.
public static void main(String[] args) {
String x = "AbC";
int[] arr = new int[x.length()];
for (int i = 0; i < x.length(); i++) {
arr[i] = Character.toLowerCase(x.charAt(i)) - 'a' + 1;
}
System.out.println(Arrays.toString(arr));
}
Output:
[1, 2, 3]
Since you seem to be case agnostic, you might want to uppercase or lowercase the string first, but you'd want to be locale-aware:
// If you don't state a locale, and you are in Turkey,
// weird things can happen. Turkish has the İ character.
// Using lower case instead could lead to the ı character instead.
final String xu = x.toUpperCase(Locale.US);
for (int i = 0; i < xu.length(); ++i) {
arr[i] = xu.charAt(i) - 'A' + 1;
}
An alternative loop would use:
// Casing not necessary.
for (int i = 0; i < x.length(); ++i) {
// One character
String letter = x.substr(i, i+1);
// A is 10 in base 11 and higher. Z is 35 in base 36.
// Subtract 9 to have A-Z be 1-26.
arr[i] = Integer.valueOf(letter, 36) - 9;
}

Categories

Resources