java - checking number is power of 2 for numbers greater than 2^64, implementation of manual division -
i trying check if number (input string
) power of 2. problem number might greater 2^64
(long long limit). if store in double
cannot binary operations on (so trick v & (v - 1) == 0
not work). here solution stumbled upon:
public class solution { public int power(string a) { string dividend = a; stringbuilder str; if (a == null || a.length() == 0) return 0; if (a.length() == 1 && a.charat(0) == '0') return 0; while (dividend.length() > 0 && !dividend.equalsignorecase("2")) { str = new stringbuilder(); int carry = 0; int n = dividend.length(); if (n > 0) { int num = dividend.charat(n - 1) - '0'; if (num % 2 == 1) return 0; } (int = 0; < n; i++) { char c = (char) (dividend.charat(i) - '0'); int res = c + 10 * carry; c = (char) (res / 2 + '0'); carry = res % 2; str.append(c); } if (str.charat(0) == '0') str.deletecharat(0); dividend = str.tostring(); } return 1; } }
i having problems understanding solution. first check done if number odd or not. having problems understanding implementation of manual division done in problem (especially arithmetic operations involving both char , int). '0' == 48
, subtracting '0'
character converts integer value. can explain me how division operation has been implemented here? thanks!
the easiest way understand implementation pen , paper test. skip part understood , focus on last for
loop.
let's take "50"
example-input. loop steps through string
character-wise, starting on left. therefore, first character processed '5'
. know, 5
odd. means have "carry" next division. result of 5 / 2
2
. 2
first digit of result in division. notice if reverse our steps, 2 * 2
, 4
. reason have carry on (the 1
missing, since 5 - 4
1
). may notice that, if divide 2, can either carry 0
(nothing) or 1
(if , if dividend odd).
now on next digit, 0
. have carry 1
last division on step. since moved 1 digit left, 1
previos step becomes 10
in step. moved "one order of magnitude down", therefore have multiply carryed part 10
. means calculate (0 + (1 * 10)) / 2
, 10 / 2
= 5
. 5
second digit of result. since dividend even, need nothing carry over.
the final ouput therefore "25"
, expected.
Comments
Post a Comment