Solution Idea

50023. Combination Lock

參考解法

locker.c

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
32
#include "locker.h"
 
#define UNLOCK 0
#define LOCKED 1
#define OPERROR -1
#define PEERROR 10000
void init(Lock *lock) {
    lock->status = UNLOCK;
}
int lock(Lock *lock, int combination) {
    if (lock->status == LOCKED)
        return OPERROR;
    if (combination < 0 || combination >= 10000)
        return PEERROR;
    lock->status = LOCKED;
    return lock->pwd = combination;
}
int unlock(Lock *lock, int combination) {
    if (lock->status == UNLOCK)
        return OPERROR;
    if (lock->pwd != combination)
        return LOCKED;
    return lock->status = UNLOCK;
}
int isLocked(Lock *lock) {
    return lock->status;
}
 
#undef PEERROR
#undef OPERROR
#undef LOCKED
#undef UNLOCK

locker.h

1
2
3
4
5
6
7
8
9
10
11
12
#ifndef _LOCKER_H
#define _LOCKER_H
 
typedef struct {
    int status, pwd;
} Lock;
 
void init(Lock *lock);
int lock(Lock *lock, int combination);
int unlock(Lock *lock, int combination);
int isLocked(Lock *lock);
#endif

Discussion