thafnhlong / hackerrank-storage

0 stars 0 forks source link

https://www.hackerrank.com/challenges/closest-number #54

Open thafnhlong opened 2 years ago

thafnhlong commented 2 years ago

Constraint:

X >= 1 <=1e9 A >= 1 <=1e9

A = 1 B < 0 => 1 B = 0 => 1 B > 0 => 1 A > 1 B < 0 => 0 B = 0 => 1 B > 0 => round(A^B/X)*X

Rút gọn 1:

  1. A=1=>1 X=1 => 1 X>1 => 0
  2. B<0=>0 any X => 0
  3. B=0=>1 X=1 => 1 X>1 => 0
  4. B>0=>ROUND

Rút gọn 2:

  1. A=1 || B=0: X=1 => 1 X>1 => 0
  2. B<0 => 0
  3. ROUND

Code

int closestNumber(int a, int b, int x) {
    if(a==1 || b==0){
        if (x==1) return 1;
        return 0;
    }
    if (b<0) return 0;
    return (long)(round(pow(a,b)/x))*x;
}