/* A number is a multi number if its decimal representation can be split into two numbers, such that the product of all the digits in the first number is equal to the product of all the digits in the second number. For example, 1221 is a multi number because it can be split into 12 and 21, and 1 * 2 = 2 * 1. 1236 is also a multi number, but 1234 is not. Note that you can only split a number into two sequences of consecutive digits, where each sequence contains at least one digit. So, for example, we can only split 12345 in four different ways: 1-2345, 12-345, 123-45, 1234-5. You will be given an int number. Return "YES" if it is a multi number, or "NO" otherwise (all quotes for clarity). */ #include <iostream> #include <iomanip> #include <conio.h> int getProduct(int x) { int p = 1; // returns the product of the digits of the number passed // single statement idiom for(int n = x; n > 0; p = p*(n%10), n = n/10); return p; } bool isMultiNumber(int n) { int m = 0; // multiplier to generate sub-numbers int pr = -1; // previous remainder while(true) { int q = n / 10; int r = n % 10; // do we have previous remainder, if yes // multiply the remainder and add to previous remainder if(pr != -1) r = (r * 10) + pr; // are we done with all the passes ? if(q == 0) return false; if(getProduct(q) == getProduct(r)) return true; n = q; pr = r; } } int main() { // some tests assert(getProduct(123)== 6); assert(getProduct(10)== 0); assert(getProduct(999)== 729); assert(getProduct(1)== 1); assert(getProduct(3456)== 360); assert(isMultiNumber(1221) == true); assert(isMultiNumber(1236) == true); assert(isMultiNumber(1234) == false); assert(isMultiNumber(123) == false); assert(isMultiNumber(2306) == true); std::cout << "all tests passed !" << std::endl; getch(); }
Yet another blog from yet another software engineer - a collection of my thoughts and some snippets of code I write (mainly for my later reference). If you find this useful, lets discuss in comments.
November 27, 2012
multi-number
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment