Square Every Digit

kata programming

توضیح:

در این کاتا برنامه نویسی، می خواهیم هر یک از عددهای یک عدد را به توان ۲ برسانیم و به هم اضافه کنیم.

برای مثال، اگر عدد ما 9119 باشد، تابع ما باید عدد 811181 را بر گرداند، چون ۹۲ می شود ۸۱ و ۱۲ می شود ۱

Description:

Welcome. In this kata, you are asked to square every digit of a number and concatenate them.

For example, if we run 9119 through the function, 811181 will come out, because 92 is 81 and 12 is 1.

Note: The function accepts an integer and returns an integer

public class SquareDigit {

    public static int squareDigits(int n) {
		String input = "" + n;
		String result = "";
		for (char character : input.toCharArray()) {
			int square = Integer.parseInt("" + character);
			square *= square;
			result += square;
		}
		return Integer.parseInt(result);
	}

}
import java.util.stream.Collectors;

public class SquareDigit {

    public int squareDigits(int n) {
        return Integer.parseInt(String.valueOf(n)
                                      .chars()
                                      .map(i -> Integer.parseInt(String.valueOf((char) i)))
                                      .map(i -> i * i)
                                      .mapToObj(String::valueOf)
                                      .collect(Collectors.joining("")));
    }

}
public class SquareDigit {
  private static final int BASE = 10;
  
  public int squareDigits(int n) {
    if (n < BASE) {
      return n * n;
    }
    int digit = n % BASE;
    int squaredDigit = digit * digit;
    return squaredDigit + (squaredDigit < BASE ? BASE : BASE * BASE) * squareDigits(n / BASE);
  }
}
public class SquareDigit {

  public int squareDigits(int n) {
  
    String strDigits = String.valueOf(n);    
    String result = "";
    
    for (char c : strDigits.toCharArray()) {
      int digit = Character.digit(c, 10);
      result += digit * digit;
    }
    
    return Integer.parseInt(result);
  }

}
public class SquareDigit {

  public int squareDigits(int n) {
    
    //Use StringBuffer due to performance
    final StringBuffer result = new StringBuffer();
    int x = 0;
    
    //As long as we have digits left.
    while (n > 0) {
      
      //Take the next digit (we are in the decimal system).
      x = n % 10;
      
      //Delete this digit.
      n = n / 10;
      
      //Insert at the first position is necessary otherwise we would get a wrong order.
      result.insert(0, x * x);
    }
    
    return Integer.parseInt(result.toString());
  }

}
public class SquareDigit {

  public int squareDigits(int n) {
      if (n < 10) return n * n;
      else {
        int h = squareDigits(n / 10);
        int l = n % 10;
        return Integer.parseInt(h + "" + l * l);
      }
  }

}

دیدگاهتان را بنویسید