Aishu
Aishu

Reputation: 1320

Multiply the number based on its length

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

Upvotes: 2

Views: 691

Answers (4)

Oleg Cherednik
Oleg Cherednik

Reputation: 18245

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

Upvotes: 1

azro
azro

Reputation: 54148

  1. 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;
    }
    
  2. 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';

Upvotes: 1

bkis
bkis

Reputation: 2587

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))).

Upvotes: 3

rzwitserloot
rzwitserloot

Reputation: 102902

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.

Upvotes: 0

Related Questions