Problem 9: ruby rewrite

This commit is contained in:
Ivan R. 2022-11-28 22:34:01 +05:00
parent eda9b3a868
commit a70c532a3e
No known key found for this signature in database
GPG key ID: 56C7BAAE859B302C
6 changed files with 31 additions and 55 deletions

View file

@ -1 +0,0 @@
../template/Makefile

View file

@ -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;
}

View file

@ -1,4 +0,0 @@
#pragma once
#include <stdbool.h>
bool isPalindrome(int x);

View file

@ -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;
}

View 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

View 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