diff --git a/FractionToRecurringDecimal.php b/FractionToRecurringDecimal.php new file mode 100644 index 0000000..b92712e --- /dev/null +++ b/FractionToRecurringDecimal.php @@ -0,0 +1,91 @@ + O(n), где n - количество цифр в итоговом остатке. + * + * @param Integer $numerator + * @param Integer $denominator + * @return String + */ + function fractionToDecimal($numerator, $denominator) { + if ($numerator === 0) { + return "0"; + } + + $sign = ''; + if ($numerator < 0 && $denominator > 0 || $numerator > 0 && $denominator < 0) { + $sign = '-'; + } + + $numerator = abs($numerator); + $denominator = abs($denominator); + + $quotient = $sign . (int) floor($numerator / $denominator); + $remainder = $numerator % $denominator; + + if ($remainder === 0) { + $this->hash[$remainder] = $quotient; + + if (count($this->hash) === 1) { + return implode('', $this->hash); + } + $first = array_shift($this->hash); + return $first . '.' . implode('', $this->hash); + + } + + if (array_key_exists($numerator, $this->hash)) { + $this->hash[$numerator] = "({$quotient}"; + $this->hash[] = ")"; + $first = array_shift($this->hash); + return $first . '.' . implode('', $this->hash); + } + + if ($this->first) { + $this->hash['first'] = $quotient; + $this->first = false; + } else { + $this->hash[$numerator] = $quotient; + } + + + return $this->fractionToDecimal($remainder * 10, $denominator); + } +} diff --git a/IntersectionOfTwoLinkedListsSolution.php b/IntersectionOfTwoLinkedListsSolution.php new file mode 100644 index 0000000..40ef607 --- /dev/null +++ b/IntersectionOfTwoLinkedListsSolution.php @@ -0,0 +1,125 @@ +headA)) { + $this->headA = $headA; + } + if (empty($this->headB)) { + $this->headB = $headB; + } + + $nextA = !empty($headA) ? $headA->next : $this->headB; + $nextB = !empty($headB) ? $headB->next : $this->headA; + + return $this->getIntersectionNodeRecursive($nextA, $nextB); + } + + /** + * Сложность O(n + m) по времени и O(1) по памяти, итеративно и через 2 указателя. + * + * @param ListNode $headA + * @param ListNode $headB + * @return ListNode + */ + function getIntersectionNodeIterative($headA, $headB) + { + if ($headA === $headB) { + return $headA; + } + + $a = $headA; + $b = $headB; + + while ($a !== $b) { + $a = !empty($a) ? $a->next : $headB; + $b = !empty($b) ? $b->next : $headA; + } + + return $a; + } +} + +class ListNode +{ + public $val = 0; + public $next = null; + + function __construct($val) + { + $this->val = $val; + } +}