ちょっといろいろと復習をしようと思い至っている今日この頃。
渡された整数の桁をひっくり返して返す関数を。
#include <math.h>

int rev(int org) {
  int ret = 0;
  int fig = log10(org);

  while (fig >= 0) {
    ret += (org % 10) * pow(10, fig);
    org /= 10;
    fig--;
  }
  
  return ret;
}
Posted by setomits at 01:44 | Comments: 6
Re: 整数の桁の入れ替え
C++ 版。負の値は大丈夫?
string::reverse()ってないんだっけ?


#include<iostream>
#include<string>
#include<algorithm>
#include<sstream>
#include<cstdlib>

int rev_cpp(int org) {
std::ostringstream os;
os << org;
std::string org_s = os.str();
std::string r;
copy(org_s.rbegin(), org_s.rend(), r.begin());
return std::strtol(r.c_str(), NULL, 10);
}


無駄に遅そう。
Posted by kharakawa at 05:18 on 2007 Sep 29th
Re: 整数の桁の入れ替え
string を使うのはずるいような気がしたけど、そして rbegin(), rend() なんてのが用意されているにも関わらず、 reverse() は無いんだ!

さておき、負の場合は考えてなかったなあ。
ということで、負でも大丈夫なように。

#include <math.h>

int rev(int org) {
int ret = 0;
int fig = 0;
int neg = 0;

if (org < 0) {
neg = 1;
org *= -1;
}

fig = log10(org);

while (fig >= 0) {
ret += (org % 10) * pow(10, fig);
org /= 10;
fig--;
}

if (neg)
return ret * -1;
else
return ret;
}
Posted by setomits at 11:58 on 2007 Sep 29th
Re: 整数の桁の入れ替え
な、なんで、整数の演算ごときにlogとか使うのー!

これで十分でしょ?


int rev(int a){
int r=0;
while(a!=0){
r=r*10+a%10;
a/=10;
}

return r;
}
Posted by おぢさん at 01:37 on 2007 Sep 30th
Re: 整数の桁の入れ替え
そっかー、なるほどなあ。
ありがとうございます。
Posted by setomits at 02:39 on 2007 Sep 30th
Re: 整数の桁の入れ替え
> string を使うのはずるいような気がしたけど

だってここでの目的は「いかに無駄にC++ぽく書くか」だから。
テンプレートとか使わないだけヘタれかとw
Posted by kharakawa at 03:00 on 2007 Sep 30th
Re: 整数の桁の入れ替え
これだと割算を一回しかしないので一番速いはず。


#include <stdlib.h>

int rev(int n){
int r=0;
while(n!=0){
div_t t=div(n,10);

r=r*10+t.rem;
n=t.quot;
}

return r;
}

Posted by おぢさん at 12:19 on 2008 Mar 4th
Leave a comment
Required fields are marked with *
search
calendar
Feb 2012
SunMonTueWedThuFriSat
   1234
567891011
12131415161718
19202122232425
26272829   
archives
photos on flickr
www.flickr.com