Problem 9: ruby rewrite
This commit is contained in:
parent
eda9b3a868
commit
a70c532a3e
6 changed files with 31 additions and 55 deletions
|
@ -1 +0,0 @@
|
|||
../template/Makefile
|
|
@ -1,32 +0,0 @@
|
|||
#include "lib.h"
|
||||
|
||||
bool isPalindrome(int x) {
|
||||
if (x < 0)
|
||||
return false;
|
||||
|
||||
// Find length and calculate divisor
|
||||
int len = 0;
|
||||
int div = 1;
|
||||
int copy = x;
|
||||
while (copy > 0) {
|
||||
copy /= 10;
|
||||
if (len != 0)
|
||||
div *= 10;
|
||||
len++;
|
||||
}
|
||||
|
||||
// Compare digits
|
||||
for (int i=0; i<len/2; i++) {
|
||||
int a = x / div;
|
||||
int b = x % 10;
|
||||
if (a != b)
|
||||
return false;
|
||||
|
||||
// Remove first and last digit
|
||||
x = x % div;
|
||||
x /= 10;
|
||||
div /= 100;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
|
@ -1,4 +0,0 @@
|
|||
#pragma once
|
||||
#include <stdbool.h>
|
||||
|
||||
bool isPalindrome(int x);
|
|
@ -1,18 +0,0 @@
|
|||
#include <stdio.h>
|
||||
#include "lib.h"
|
||||
|
||||
int main() {
|
||||
int a = 121;
|
||||
printf("Test 1: %d\n", isPalindrome(a) == 1);
|
||||
|
||||
int b = -121;
|
||||
printf("Test 2: %d\n", isPalindrome(b) == 0);
|
||||
|
||||
int c = 1234554321;
|
||||
printf("Test 3: %d\n", isPalindrome(c) == 1);
|
||||
|
||||
int d = 2147483647;
|
||||
printf("Test 4: %d\n", isPalindrome(d) == 0);
|
||||
|
||||
return 0;
|
||||
}
|
15
problems/9-palindrome-number/main.rb
Normal file
15
problems/9-palindrome-number/main.rb
Normal file
|
@ -0,0 +1,15 @@
|
|||
# @param {Integer} x
|
||||
# @return {Boolean}
|
||||
def is_palindrome(x)
|
||||
return false if x.negative?
|
||||
|
||||
copy = x
|
||||
inv = 0
|
||||
|
||||
while copy.positive?
|
||||
inv = inv * 10 + copy % 10
|
||||
copy /= 10
|
||||
end
|
||||
|
||||
inv == x
|
||||
end
|
16
problems/9-palindrome-number/test.rb
Normal file
16
problems/9-palindrome-number/test.rb
Normal file
|
@ -0,0 +1,16 @@
|
|||
require_relative 'main'
|
||||
require 'test/unit'
|
||||
|
||||
class TestIsPalindrome < Test::Unit::TestCase
|
||||
def test_palindrome
|
||||
assert_equal(true, is_palindrome(121))
|
||||
end
|
||||
|
||||
def test_negative
|
||||
assert_equal(false, is_palindrome(-121))
|
||||
end
|
||||
|
||||
def test_regular_number
|
||||
assert_equal(false, is_palindrome(10))
|
||||
end
|
||||
end
|
Loading…
Reference in a new issue