You are given a positive integer n. The beauty factor of a number is the sum of digits obtained till the obtained sum is a single digit.
Example:
Input: b=5, k=3
Output: 149
Approach
Java
public class BeautyFactor {public static void main(String[] args) {int b = 5;int k = 3;if (k != 9) {int x = binaryExponentiation(10, k - 1) / 9;int y = binaryExponentiation(10, k) / 9;boolean flag = false;for (int i = x; i <= y; i++) {if (check(i * 9 + b, k)) {System.out.println(i * 9 + b);flag = true;break;}}if (!flag)System.out.println(-1);} else {if (b == 9)System.out.println(123456789);elseSystem.out.println(-1);}}static int binaryExponentiation(int x, int n) {int result = 1;while (n > 0) {if (n % 2 == 1)result = result * x;x = x * x;n = n / 2;}return result;}static boolean check(int x, int k) {int h[] = new int[10];while (x > 0) {h[x % 10]++;x /= 10;}if (h[0] != 0)return false;int count = 0;for (int i = 1; i < 10; i++) {if (h[i] > 1)return false;if (h[i] == 1)count++;}return count == k;}}
No comments:
Post a Comment