Algorithm/Codility

Lesson1. BinaryGap

hamaganatanadda 2019. 6. 19. 09:04

L : https://app.codility.com/programmers/lessons/1-iterations/binary_gap/ 

 

Q : 10진수를 받아서 2진수로 변환하여 1과 1사이에 0의 개수가 제일 많은걸 찾아내야 하는 문제이다.

 

A : 델파이에서는 10진수를 2진수로 바꾸는 방법을 찾지 못 해서 변환규칙으로 로직을 작성

 

[Delphi]

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
uses SysUtils;
function solution(N: longint): longint;
var
  iVal, iCnt, iPastCnt, iMod : longint;
  sVal : String;
  bFlag : Boolean;
begin
  iVal := N;
  iCnt := 0;
  iPastCnt := 0;
 
  while iVal >= 1 do 
  begin
    iMod := iVal Mod 2; 
    sVal := IntToStr(iMod) + sVal;
    
    if iMod = 1 then 
    begin
      bFlag := True;
      if iCnt > iPastCnt then iPastCnt := iCnt;
      iCnt := 0;
    end;
    
    if (bFlag) and (iMod = 0) then Inc(iCnt);
    
    iVal := iVal div 2;
  end;
 
  exit(iPastCnt);
    
end; 
cs

 

※ 수정할 부분이 있으면 알려주세요. 로직 짠 후 구글링으로도 참고합니다. 

'Algorithm > Codility' 카테고리의 다른 글

Lesson3-3. TapeEquilibrium  (0) 2019.06.22
Lesson3-2. PermMissingElem  (0) 2019.06.20
Lesson3-1. FrogJmp  (0) 2019.06.20
Lesson2-2. CyclicRotation  (0) 2019.06.20
Lesson2-1. OddOccurrencesInArray  (0) 2019.06.20